mysql populate_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,必须按照顺序查找引用。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值