V. *_*bor 9 mongoose mongodb node.js
在我使用 mongoose 的节点 js 项目中,我试图更新文档中的数组项。
我有一个users
架构,里面有一个notifications
数组。每个用户都有一个_id
,每个通知项都有一个_id
。
如何通过用户 ID 和通知 ID 更新通知?
用户架构:
const schema = mongoose.Schema({
notifications: [{
id: { type: mongoose.Schema.ObjectId },
title: { type: String },
body: { type: String },
isRead: { type: Boolean, default: false },
date: { type: Date }
}],
token: { type: String },
isActive: { type: Boolean, default: false }
}, { timestamps: {} })
Run Code Online (Sandbox Code Playgroud)
这是我迄今为止尝试过的:
exports.updateNotification = (req, res) => {
// Note: in req.params I receive id(for user id) and notificationId.
UserModel.findByIdAndUpdate(req.params.id, { $set: { notifications: req.body } }, { safe: true, upsert: true, new: true })
.then((result) => res.status(201).json({
success: true,
message: res.__('success.add'),
user: result
}))
.catch(err => errorHandler.handle(err, res))
}
Run Code Online (Sandbox Code Playgroud)
该方法findByIdAndUpdate
我用它来更新的用户,但我不知道如何去适应它更新的通知,通过ID。
ViK*_*KiG 12
尝试使用$elemMatch
,
UserModel.findOneAndUpdate({_id: 1, notifications: {$elemMatch: {id: 2}}},
{$set: {'notifications.$.title': req.body.title,
'notifications.$.body': req.body.body,}}, // list fields you like to change
{'new': true, 'safe': true, 'upsert': true});
Run Code Online (Sandbox Code Playgroud)