我有这个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})
答案 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
});