【问题标题】:Mongoose Find subdocument in arrayMongoose 在数组中查找子文档
【发布时间】:2020-01-10 03:44:07
【问题描述】:

我在 Robo3t 中有以下数据 使用此模型:

const eleccionSchema = new mongoose.Schema({
    e: [{
        id: {
            type: String,
            required: true
        },
        l:[...]
    }],
    eleccion: {
        type: Number,
        required: true,
        ref: 'Corte'
    }
})
//? Create the model
const Eleccion = mongoose.model('Eleccion', eleccionSchema)

现在我正在尝试像这样根据 e.id 获取一些数据

const eleccion = await Eleccion.findOne({'e.id':'A'})

但它实际上是返回整个数组而不是一个

【问题讨论】:

    标签: mongodb mongoose mongoose-schema


    【解决方案1】:

    用投影修复它:https://docs.mongodb.com/manual/reference/operator/projection/elemMatch/

    const eleccion = await Eleccion.findOne({}, {
     'e':
       { $elemMatch: { id: 'A' } }
    })
    

    【讨论】:

      猜你喜欢
      • 2016-01-19
      • 2022-10-01
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      • 2014-11-27
      • 2021-09-30
      • 2013-05-26
      相关资源
      最近更新 更多