猫鼬 - 搜索复杂的嵌套文档并更新子文档的某些字段



我正在尝试根据邮递员 req.body 提供的键更新猫鼬子文档的某些字段。

我已经尝试了一些解决方案,但没有成功的结果。我想遍历 req.body 并更新必要的字段。就像我在"//更新功能"下尝试过

一样这是我的架构。

_id: mongoose.Schema.Types.ObjectId,
profile: {
full_name: {
first_name: String,
last_name: String
},
phone: Number,
email: String,
gender: String,
address: {
city: String,
street: String,
},
occupation: String,
biography: String
},
password: {
type: String,
required: true
},
}, {
timestamps: {
createdAt: 'created_at'
}
})
module.exports = mongoose.model('Assistant', assistantSchema);

这是我的更新路线,我想在其中更新值

router.patch('/:assistantId', Check_Auth, async (req, res, next) => {
const id = req.params.assistantId;
//update function
const updateParams = req.body;
const set = {};
for (const field of updateParams) {
set['assistant.$.' + field.key] = field.value
}
//update
try {
await Assistant.updateOne({
_id: id
}, {
$set: set
}).exec().then(result => {
console.log(result);
res.status(201).json(result)
}).catch(err => {
console.log(err);
res.status(403).json({
errmsg: "Ooh something happen, Not able to update profile try again"
})
})
} catch (err) {
res.status(500).json({
errmsg: err
})
}
});

这是我的价值观 邮递员

[
{"key": "phone", "value": "651788661"},
{"key": "email", "value": "dasimathias@gmail.com"},
{"key": "city", "value": "douala"},
{"key": "street", "value": "bonaberi"},
{"key": "biography", "value": "just share a little code"}
]
```

给定您作为 post 请求发送的数据,您传递给$set的对象如下所示:

{ 'assistant.$.phone': '651788661',
'assistant.$.email': 'dasimathias@gmail.com',
'assistant.$.city': 'douala',
'assistant.$.street': 'bonaberi',
'assistant.$.biography': 'just share a little code' }

这与您的架构不一致,如果您尝试更新profile属性,您将执行以下操作:

for (const field of updateParams) {
if(field.key == "city") set[`profile.address.${field.key}`] = field.value
else set[`profile.${field.key}`] = field.value
}

这给一个对象set如下所示:

{ 'profile.phone': '651788661',
'profile.email': 'dasimathias@gmail.com',
'profile.address.city': 'douala',
'profile.street': 'bonaberi',
'profile.biography': 'just share a little code' 
}

请注意,city嵌套在address中,因此您需要访问它,您必须对full_name执行相同的(条件)。
如果要更新子文档数组:

set[`assistant.$.profile.address.${field.key}`]
set[`assistant.$.profile.${field.key}`]

最新更新