javascript - 在Mongoose中引用另一个模式

如果我有两个模式,如:

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
Gorkem Yurtseven asked 2019-08-24T13:16:29Z
2个解决方案
148 votes

听起来像填充方法就是你要找的东西。 首先对您的帖子架构进行小的更改:

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
});
nicksweet answered 2019-08-24T13:16:57Z
18 votes

附录:没有人提及" Populate" ---非常值得您花时间和金钱看Mongooses Populate方法:还解释了交叉文档引用

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

fino answered 2019-08-24T13:17:28Z
translate from https://stackoverflow.com:/questions/18001478/referencing-another-schema-in-mongoose