【发布时间】:2020-06-30 17:58:46
【问题描述】:
嗨,我是 mongoose 和 mongodb 的新手。我想从文档中的数组中删除特定对象并返回更新后的文档。我已经尝试了很多,但它总是返回 null。这是我的文档结构。
{
"role": "Student",
"skills": [
"html",
"css",
"js"
],
"_id": "5ef583198e9b23cc8c606c10",
"user": "5ee5c9ef26333935647e54bc",
"__v": 24,
"status": "Intern",
"education": [],
"internships": [
{
"current": false,
"_id": "5ef894d48f601512340f25b5",
"title": "Web",
"company": "asdfadfd",
"from": "2010-02-04T00:00:00.000Z"
},
{
"current": false,
"_id": "5ef894f31dc9413bf89c44d8",
"title": "Django",
"company": "example",
"from": "2010-02-04T00:00:00.000Z"
}
]
}
这是我的更新功能
exports.deleteStudentInternship = async (req, res, next) => {
const deleteInternship = await Student.findOneAndUpdate(
{ $and: [{ user: req.user.id }, { 'internships': { $elemMatch: { _id: req.params.intern_id } } }] },
{ '$pull': { 'internships': { _id: req.params.intern_id } } },
{
new: true,
useFindAndModify: false,
},
function (error) {
if (error) return validationError(404, { internship: 'Internship id not exist' }, next)
}
);
if (!deleteInternship) {
return validationError(404, { internship: 'Internship id not exist' }, next)
}
res.status(200).json(deleteInternship);
}
【问题讨论】:
-
您的文档更新了吗?
-
是的文档更新成功,但执行后返回 null 我想要更新的文档
-
您可以尝试删除
function (error) {}回调吗?您在async/await旁边使用回调,这可能会导致意外行为 -
是的,我试过了。
-
而
deleteInternship仍然是null?
标签: node.js mongodb mongoose mongodb-query