在GET响应中看不到JSON字段(mongoose)

时间:2015-12-14 09:18:27

标签: javascript angularjs json mongodb 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字段定义为:

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

当我执行http.get获取列表时,我收到了回复:

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

为什么我看不到/使用owner字段?我需要它来操作我的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);
            });
    });

此外,我通过这样做来填充owner字段:

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

1 个答案:

答案 0 :(得分:1)

你的问题是这个

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
});