在mongoose中引用另一个模式

IT技术 javascript mongodb mongoose
2021-02-02 17:45:34

如果我有两个模式,如:

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
4个回答

听起来 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
});
populate 和 addToSet 之间有什么区别?
2021-03-22 17:45:34
@KarlMorrison “ref”的文档被埋在以下文档中populatemongoosejs.com/docs/populate.html
2021-03-27 17:45:34
“ref”字段是做什么用的?我找不到有关它的文档。
2021-04-02 17:45:34
by:selectro的参考在哪里
2021-04-09 17:45:34
@KarlMorrison ref 字段表示将在哪个集合中搜索提到的 id。
2021-04-12 17:45:34

附录:没有人提到“填充”——看mongoose填充方法非常值得你花时间和金钱:还解释了交叉文档引用

http://mongoosejs.com/docs/populate.html

回复晚了,但补充说Mongoose也有子文档的概念

使用此语法,您应该能够像这样引用您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 路线可能是要走的路。取决于您的应用程序在做什么。

{body: "string", by: mongoose.Schema.Types.ObjectId}

mongoose.Schema.Types.ObjectId会创建一个新的ID,尝试将其更改为更直接的类型,如String或Number。