我正在处理NodeJS后端API,并试图在MongoDB数据库中将对象数组中的键从false更改为true.我正在从客户端传递两个条件:用户的邮箱和向用户发送消息的人的邮箱.我想将布尔值read
改为true
.
示例数据:
{
_id: new ObjectId("6282163781acbcd969de3fc9"),
firstName: 'Amanda',
lastName: 'Nwadukwe',
role: 'Volunteer',
email: 'amandanwadukwe@gmail.com',
password: '$2a$10$YD5MQlMt0gqSULQOBNcEfOLr3vIK8eF4dqdLw3XctsIVgbnf54P32',
confirmPassword: '$2a$10$mnL0S1bDDkGVnKgqQP81mOew9aFdNTUCGOEs7LvWYRxzivN4hrtFS',
date: 2022-05-16T09:14:57.000Z,
messages: [
{
message: 'This is another message from Amanda',
sendersEmail: 'laju@gmail.com',
date: '2022-05-14T12:00:45.000Z',
read: false
},
{
sender: 'Amanda Nwadukwe',
message: 'This is another message from Amanda',
sendersEmail: 'amanda@gmail.com',
date: '2022-05-14T12:00:45.000Z',
read: false
}]
所需输出:
{
_id: new ObjectId("6282163781acbcd969de3fc9"),
firstName: 'Amanda',
lastName: 'Nwadukwe',
role: 'Volunteer',
email: 'amandanwadukwe@gmail.com',
password: '$2a$10$YD5MQlMt0gqSULQOBNcEfOLr3vIK8eF4dqdLw3XctsIVgbnf54P32',
confirmPassword: '$2a$10$mnL0S1bDDkGVnKgqQP81mOew9aFdNTUCGOEs7LvWYRxzivN4hrtFS',
date: 2022-05-16T09:14:57.000Z,
messages: [
{
message: 'This is another message from Amanda',
sendersEmail: 'laju@gmail.com',
date: '2022-05-14T12:00:45.000Z',
read: true
},
{
sender: 'Amanda Nwadukwe',
message: 'This is another message from Amanda',
sendersEmail: 'amanda@gmail.com',
date: '2022-05-14T12:00:45.000Z',
read: false
}]
我try 了很多过滤的方法,但都没有成功.这是我将所有read
改为true
的代码.它也不起作用.
app.post("/view_message", (req, res) => {
const email = req.body.email;
Users.findOneAndUpdate({ "email": email }, {$set:{"messages.$.read": true}}, (err, result) => {
console.log(result)
})
});