简体   繁体   English

Mongoose通过ObjectID引用查找

[英]Mongoose find by ObjectID reference

I have two schemas: 我有两个架构:

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

And town schema: 和城镇架构:

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

I need to make query that finds all Ads by town.name How can I do that? 我需要通过town.name查找找到所有广告的查询。我该怎么做?

You can request a town by name and use the mongoose populate method to fill the ads Array from town object. 您可以按名称请求城镇,并使用mongoose populate方法从城镇对象填充广告数组。

You can find examples in the mongoose documentation: 您可以在mongoose文档中找到示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM