如果数据库中不存在该数组字段值,如何推入该数组字段值?

时间:2019-06-12 12:08:59

标签: node.js mongodb mongoose mongodb-query

我的后端具有此功能:

exports.updatePacienteByCodigo = function (req, res) {
let codPaciente = req.params.codPaciente;
let params = req.body; // This is the data what come from frontend = {'testRealizados':['example'], 'respuestas':['example'], 'codMedico':'example'}
Paciente.findOneAndUpdate({ codPaciente: codPaciente }, {
    '$push': {
        'testsRealizados': params.testsRealizados,
        'respuestas': params.respuestas,
        'codMedico': {'$ne':params.codMedico} //here is the problem
    }
}).then(
    pacienteEncontrado => {
        if (!pacienteEncontrado) {
            res.status(404).send({ accion: 'updatePaciente', mensaje: 'Ese paciente no existe' });
        } else {
            res.status(200).send({ accion: 'updatePaciente', mensaje: 'Paciente actualizado correctamente' });
        }
    }
).catch(err => { res.status(500).send({ accion: 'updatePaciente', mensaje: 'Error ' + err }) })
};

此查询向我抛出此错误"Error CastError: Cast to [string] failed for value \"[{\"$ne\":\"o8qjdeli\"}]\" at path \"codMedico\""}

我想做的是,如果codMedico在数据库中的值与参数codMedico的值相同,则不更新该字段。

我尝试过,但是没有用。我没有想法,所以我在这里。谢谢。

[已解决]

我尝试了$ addToSet方法,它的工作方式就像@Plancke在评论中告诉我的一样。

1 个答案:

答案 0 :(得分:0)

我尝试了$ addToSet方法,它的工作方式就像@Plancke在评论中告诉我的一样。