首页 > 解决方案 > Mongoose 在填充数组中查找术语

问题描述

我有两个系列:ConsultasPacientes. 我试图通过一个术语来咨询病人的名字,但没有成功。

var consultaSchema = new Schema({

    //detalles de la consulta
    paciente_c: { type: Schema.Types.ObjectId, ref: 'Paciente', required: true },
    medio_c: { type: String, required: false },
    /* ... */
}, { timestamps: true } );

module.exports = mongoose.model('Consulta', consultaSchema);

var pacienteSchema = new Schema({

    nombre: { type: String, required: [true, 'El nombre es necesario']},
    apellido: { type: String, required: false },
    /* ... */
}, { timestamps: true } );

module.exports = mongoose.model('Paciente', pacienteSchema);

和查询:

Consulta.find({})
    .populate('paciente_c', 'nombre apellido')
    //.or( { paciente_c: { nombre: regex } } )
    .or( { 'paciente_c.nombre': regex } )
    .exec( (err, consultas )=> {
        if (err) {
            reject('Error al cargar consultas !!!', err);
        } else {
            resolve(consultas)
        }
    });

编辑: 添加以下行

.populate( 'paciente_c', null, { nombre: { $in: regex } } )

该查询带来了所有的咨询,并且只填充了它找到该术语的“患者_c”,但这不是我需要的。我只想获取找到该术语的查询,而不是全部。

编辑2: 以下行工作正常,但它如何在两个值之间进行比较?

return new Promise((resolve, reject)=> {

    Consulta.find({})
        .populate({
            path: 'paciente_c',
            match: { nombre: { $in: regex } }
        })
        .exec( (err, consultas )=> {
            if (err) {
                reject('Error al cargar consultas !!!', err);
            } else {
                consultas = consultas.filter(c => c.paciente_c != null);
                resolve(consultas)
            }
        });
});

标签: node.jsmongodbmongoosemongoose-populate

解决方案


推荐阅读