在Mongoose中引用另一个模式 [英] Referencing another schema in Mongoose

查看:494
本文介绍了在Mongoose中引用另一个模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个模式,如:

if I have two schemas like:

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}],
});

我尝试将它们连接在一起,就像上面的例子一样,但我无法弄清楚如何做到这一点。最终,如果我可以做这样的事情,那将使我的生活变得非常轻松

I tried to connect them together like the example above but I couldn't figure out how to do it. Eventually, if I can do something like this it would make my life very easy

var profilePic = Post.postedBy.profilePic


推荐答案

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

It sounds like the populate method is what your looking for. First make small change to your post schema:

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);

然后,当您进行查询时,可以填充这样的引用:

Then, when you make your query, you can populate references like this:

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

这篇关于在Mongoose中引用另一个模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆