javascript – 无法在GET响应中看到JSON字段(mongoose)

我有这个 JSON文档(如 mongolab所示):

{
    "_id": {
        "$oid": "566e8673eb862d165fef7171"
    },
    "street": "Dizingof",
    "buildingNumber": 33,
    "apartmentNumber": 63,
    "beds": 3,
    "owner": {
        "_id": {
            "$oid": "564374944cb813541afc193a"
        },
        "local": {
            "password": "$2a$08$PtZrvLY7MWSi44gMDSjLJ.u4x.IOXIkRFZYfQhAwt.5vSIXpCYjX6",
            "email": "someemail@gmail.com"
        },
        "__v": 0
    }
}

其架构中的所有者字段定义为:

owner           :  {
                type: Schema.ObjectId,
                ref: 'User'
        }

当我执行http.get获取我收到的列表时:

{
  "_id": "566e8673eb862d165fef7171",
  "street": "Dizingof",
  "buildingNumber": 33,
  "apartmentNumber": 63,
  "beds": 3,
  "imagesAndCount": [],
  "UsersAndQuestions": []
}

为什么我看不到/使用所有者字段?我需要它来操作我的HTML文档.

编辑:这是routes.js中的相关GET:

app.get('/api/listing/:street/:buildingNumber/:apartmentNumber', function (req, res) {
        Listing.findOne(
            {
                "street": req.params.street,
                "buildingNumber": req.params.buildingNumber,
                "apartmentNumber": req.params.apartmentNumber
            }
            , function (err, listing) {
                if (err) { return next(err); }
                res.json(listing);
            });
    });

此外,我通过这样做填充了所有者字段:

var myUser = db.users.findOne()
db.listings.insert({"street" : "Dizingof", "buildingNumber" : 33, "apartmentNumber" : 63, "beds": 3, "owner": myUser})

最佳答案 你的问题是这个

owner :{
    type: Schema.ObjectId,
    ref: 'User'
}

Mongoose期待对文档的引用,然后使用populate进行水合(顺便说一下,它仅适用于类型数组),因此不会将其作为查询的一部分返回.

假设您使用的是猫鼬4.2,您可以执行以下操作:

http://mongoosejs.com/docs/subdocs.html#altsyntax

var ownerSchema= new Schema({ name: 'string', otherProperty: 'string' });

var parentSchema = new Schema({
  owner: ownerSchema
});
点赞