我有一个数据库,例如:
我需要根据用户请求,根据leadType
更新特定对象的属性_id
,例如,id: 5e8333cf4f19264d809b4e8c
。
我使用以下查询,但最终返回了空数组:
exports.change_lead_action = (req, res, next) => {
let lead_obj_id = req.body.leadObjId;
Lead.findOneAndUpdate(
{ _id: mongoose.Types.ObjectId(lead_obj_id) },
{ leads: { $elemMatch: { _id: req.body.leadId }}}, {leadType: req.body.leadType}, (err, lead) => {
console.log('updated', lead)
}
)
我不确定我要去哪里。
我也尝试使用Lead.find()
查询。虽然这返回了我所需的结果,但是我找不到从返回结果中更新属性的方法:
{
"message": "data found",
"lead": [
{
"_id": "5e8333cf4f19264d809b4e8e",
"leads": [
{
"education": {
"school": "happy kids corner",
"graduation": "some school"
},
"currentPosition": {
"title": "Salesforce developer",
"description": "Full stack programmer",
"joiningDate": "16 december 2019",
"endDate": "currently working",
"employmentType": "full-time",
"industry": "information technology"
},
"location": {
"state": "delhi",
"country": "india"
},
"leadType": "all",
"name": "Ben",
"mobile": 1524524678,
"_id": "5e8333cf4f19264d809b4e8c"
}
]
}
]
}
请帮助解决此问题。
答案 0 :(得分:0)
您的查询语法错误。这是Mongoose findOneAndUpdate的文档。
按照他们的说法,第一个参数是查询,第二个参数是更新命令。
所以您需要像这样构造它:
Lead.findOneAndUpdate(
{
_id: mongoose.Types.ObjectId(lead_obj_id),
leads: { $elemMatch: { _id: req.body.leadId }}
},
{leadType: req.body.leadType}, (err, lead) => {
console.log('updated', lead)
}