在一个使用 mongoose 的 Node 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: {} })
这是我迄今为止尝试过的:
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))
}
方法findByIdAndUpdate
我用它来更新用户,但我不知道如何调整它以通过id更新通知。
最佳答案
尝试使用$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});
关于node.js - Mongoose 通过 id 更新数组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48741974/