mongoose 使用populate 需要注意的问题

    So far we've created two Models. Our Person model has it's stories field set to an array of ObjectIds. The refoption is what tells Mongoose which model to use during population, in our case the Story model. All _ids we store here must be document _ids from the Story model. We also declared the Story _creator property as aNumber, the same type as the _id used in the personSchema. It is important to match the type of _id to the type of ref.

    Note: ObjectId, Number, String, and Buffer are valid for use as refs

    今天在使用mongoose的populate来查询ref的文档,一直查不到,花了整整一天时间了,只怪没有看完上面的描述。

   1.  在文档关联使用ref一定要注意,关联的那个model只能匹配_id这个字段,你要是搞个自动生成的啥的一概无效。列举一下吧:

var _User = new Schema({
    _id:Number,// 只支持ObjectId,Number,String,Buffer,就这几个引用类型,ref匹配的只有这个_id
    name:String,
    age:Number
});

var _Comment = new Schema({
    comments:[{
        text:String,
        created_by:{type:Number,ref:'User'}//这个User是model名称,数据类型要于_id的数据类型一致。
    }]
})

var userModel = mongoose.model('User',_User);
var commentsModel = mongoose.model('Comment',_Comment);

// 查询

commentModel.findOne({ })
    .populate('comments.created_by')
    .exec(function (err, commets) {
            console.log(err,commets);
    })

   2.  populate(ref1,ref2) ref1和ref2在源文档的顺序必须一致。

    意思是说在find后找到的文档如果使用ref,必须按照顺序查找引用。

看来文档仔细看是非常重要的。免得浪费精力时间。


转载于:https://my.oschina.net/antianlu/blog/283510

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Mongoose 中,populate 方法可以用来填充一个或多个字段的引用。当我们在一个模型中引用了另一个模型的某些属性时,我们可以使用 populate 方法来填充这些属性,以便在查询时一并返回所引用的文档。 具体使用方法如下: 1. 在定义 schema 时,使用 ref 字段来指定所引用的模型,例如: ``` const userSchema = new mongoose.Schema({ name: String, email: String }); const postSchema = new mongoose.Schema({ title: String, content: String, author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' } }); ``` 在这个例子中,postSchema 引用了 User 模型中的 _id 属性,使用 ref 字段来指定所引用的模型为 User。 2. 在查询时使用 populate 方法来填充所引用的文档,例如: ``` Post.find().populate('author').exec((err, posts) => { // 处理查询结果 }); ``` 在这个例子中,我们使用 populate 方法来填充 author 字段引用的 User 模型对应的文档。这样,在查询结果中,每个 post 文档的 author 字段将会被替换为对应的 User 文档。 除了填充单个字段,我们还可以填充多个字段,例如: ``` Post.find().populate('author').populate('comments').exec((err, posts) => { // 处理查询结果 }); ``` 这个例子中,我们首先使用 populate 方法来填充 author 字段,然后又使用 populate 方法来填充 comments 字段。这样,在查询结果中,每个 post 文档的 author 字段和 comments 字段都将会被替换为对应的文档。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值