Mongoose通过ObjectID引用查找

时间:2017-04-21 15:59:53

标签: node.js mongodb mongoose find

我有两个模式:

    let adSchema = mongoose.Schema (
    {
        author: {type: ObjectId, ref: 'User'},
        title: {type: String, required: true },
        town: {type: ObjectId, ref: 'Town', required: true},
    }
);

城镇模式:

    let townSchema = mongoose.Schema (
    {
        name: {type: String, required:true, unique:true},
        ads: [{type: ObjectId, ref: 'Ad'}]
    }
);

我需要通过town.name查找查找所有广告的查询 我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

您可以按名称申请城镇,并使用mongoose populate方法从城镇对象填充广告数组。

您可以在mongoose文档中找到示例:

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