在Mongoose中引用另一个模式


104

如果我有两个模式,如:

var userSchema = new Schema({
    twittername: String,
    twitterID: Number,
    displayName: String,
    profilePic: String,
});

var  User = mongoose.model('User') 

var postSchema = new Schema({
    name: String,
    postedBy: User,  //User Model Type
    dateCreated: Date,
    comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});

我试图像上面的示例那样将它们连接在一起,但是我不知道该怎么做。最终,如果我可以做这样的事情,那将使我的生活很轻松

var profilePic = Post.postedBy.profilePic

Answers:


182

听起来好像populate方法是您想要的。首先,对您的发布架构进行少量更改:

var postSchema = new Schema({
    name: String,
    postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
    dateCreated: Date,
    comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});

然后建立模型:

var Post = mongoose.model('Post', postSchema);

然后,当您进行查询时,可以填充如下引用:

Post.findOne({_id: 123})
.populate('postedBy')
.exec(function(err, post) {
    // do stuff with post
});

4
“ ref”字段的作用是什么?我找不到有关它的文档。
K-SO的毒性在增加。

3
@KarlMorrison ref字段表示将在哪个集合中搜索提到的ID。
Ankur Verma

populate和addToSet有什么区别?
Winnemucca

1
by:selectro的参考位置
穆罕默德·乌默尔

1
@karlMorrison“ ref”的文档被埋在以下文档中populatemongoosejs.com/docs/populate.html
Jeffrey Martinez


1

回复较晚,但补充说猫鼬还具有子文档的概念

使用这种语法,您应该可以像这样引用您userSchema的类型postSchema

var userSchema = new Schema({
    twittername: String,
    twitterID: Number,
    displayName: String,
    profilePic: String,
});

var postSchema = new Schema({
    name: String,
    postedBy: userSchema,
    dateCreated: Date,
    comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});

注意postedBy类型为的更新字段userSchema

这会将用户对象嵌入到帖子中,从而节省了使用引用所需的额外查找。有时这可能是更可取的,而其他时候可能会采用ref / populate路线。取决于您的应用程序在做什么。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.