search

Home  >  Q&A  >  body text

javascript - How to use mongoose joint query populate?

// 创建一个人物数据结构
let personSchema = mongoose.Schema({
        _id:Number,
        name:String,
        post:[{
            type:Number,
            ref:'postModel'
        }]
});

console.log(mongoose.Schema.ObjectId);
// 根据结构生成人物模型
let personModel = mongoose.model('person',personSchema);

let ObjectId = mongoose.Types.ObjectId;

// 创建一个文章数据结构
let postSchema = mongoose.Schema({
        _id:Number,
        title:String,
        author:{
            type:Number,
            ref:'personModel'
        },
        content:String
});

// 创建文章模型
let postModel = mongoose.model('post',postSchema);

Start query

postModel.find({})
    .populate('people')
    .exec((err,data)=>{
        console.log(data)
    });
    

What is the reason for this?
I changed the query using ObjectId and got the same result, mongoose version 4.10.6, node version 8.1.0

学习ing学习ing2736 days ago918

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-06-23 09:14:11

            post:[{
                type:Schema.ObjectId,
                ref:'postModel'
            }]

    Also note that the ref field must be consistent with the name of the model you registered, otherwise the populate operation will not be successful
    Refer to this
    https://github.com/YueminHu/l...
    It is recommended to go Learn MDN’s library example

    reply
    0
  • Cancelreply