【问题标题】:How to using "find()" with populate field in mongoose?如何在猫鼬中使用“find()”和填充字段?
【发布时间】:2019-11-11 21:51:57
【问题描述】:

我在同一个数据库中有 2 个集合。我需要使用 find() 仅选择“团队”等于“团队1”的“事件”

非常感谢。

我尝试按人口字段查找,但它不起作用。

 This is my Event schema
    const Event = mongoose.model('Event', new mongoose.Schema({
        title: {
            type: String,
            required: true,
            min: 3
        },
        eventType: {
            type: String,
            lowercase: true
        },
        date: {
            type: Date,
            default: Date.now()
        },
        venue: String,
        country: String,
        callLog: {
            type: String,
            max: 1000
        },
        eventImgUrl: [String],
        editedBy : {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'User'
        },
        timestamp: {
            type: String, 
            default: Date.now()
        }
    }));

This is my User schema
    const User = mongoose.model('User', new mongoose.Schema({
        username: {
            type: String,
            required: true,
            min: 3,
            lowercase: true
        },
        name: String,
        email: String,
        team: String,
        role: {
            type: String,
            enum: ['admin', 'creator', 'viewer']
        }
    }));

This is my Controller
    const events = await Event.find()
        .populate({ path: 'editedBy', select: ['name', 'team']});

    res.send(events);

【问题讨论】:

    标签: javascript express mongoose


    【解决方案1】:

    find 所有Events 具有team"team1"

    const team1Events = await Event.find({ team: "team1" });
    

    【讨论】:

    • 它不起作用,因为“团队”属性在用户的架构而不是事件的架构中。
    【解决方案2】:

    select 只是指定返回的字段。你需要使用populate match:

    await Event.find()
        .populate({ path: 'editedBy', match: { yourField: 'yourmatch' }});
    

    【讨论】:

      猜你喜欢
      • 2019-06-05
      • 2016-04-25
      • 2021-05-06
      • 2014-01-08
      • 2021-01-25
      • 1970-01-01
      • 1970-01-01
      • 2017-10-11
      • 1970-01-01
      相关资源
      最近更新 更多