[英]Mongoose reference other collection via ObjectID
我已通读了本指南,以构建数据库。 并且我理解了这一点,但是我想在自己的RESTful API中实现这个想法,但似乎与目前为止提出的目标背道而驰。
在链接的MongoDB文档中,它讨论了如何通过简单地引用ObjectID来节省空间,而我正在尝试做到这一点,并遵循此处的Mongoose人口文档。
但是在实现此功能后,我将完整的问题数据添加到我的用户,如下所示:
而不是在MongoDB中建议的方式:
{
name : 'left-handed smoke shifter',
manufacturer : 'Acme Corp',
catalog_number: 1234,
parts : [ // array of references to Part documents
ObjectID('AAAA'), // reference to the #4 grommet above
ObjectID('F17C'), // reference to a different Part
ObjectID('D2AA'),
// etc
]
由于问题的潜在规模,我不想将问题嵌入用户中,而是要引用其ID,然后使用其ID通过其问题数组获取所有特定用户的问题。 我确实设法只将数组保存在猫鼬中,但是发现我找不到如何从ID中提取完整文档并将其全部显示的方法,因此,如果可能的话,我们将不胜感激。
例
var bandSchema = new Schema({
name: String,
lead: { type: ObjectId, ref: 'people', autopopulate: true }
});
bandSchema.plugin(autopopulate);
var Band = mongoose.model('band3', bandSchema, 'bands');
Band.findOne({ name: "Guns N' Roses" }, function(error, doc) {
assert.ifError(error);
assert.equal('Axl Rose', doc.lead.name);
assert.equal('William Bruce Rose, Jr.', doc.lead.birthName);
done();
});
或者你可以尝试这个
Modelname.find({})
.populate('fieldname')
.exec(function(error, posts) {
console.log(JSON.stringify(posts, null, "\t"))
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.