[英]How can I update element in array in mongo db node js
How can I update element in array in one of my objects in database.如何更新数据库中我的一个对象中数组中的元素。
I need to update just the page value in certain title.我只需要更新特定标题中的页面值。 In last viewed I need to have multiple values.
在上次查看中,我需要有多个值。
My model looks something like this:我的 model 看起来像这样:
const userSchema = new Schema({
username: {
type: String,
required: true,
unique: true
},
lastViewed: [
{
title:{
type: String,
required: true
},
page:{
type: Number
}
}
]
});
This is my node.js express app这是我的 node.js 快递应用
router.post("/api/update",async(req, res)=>{
let {token} = req.body;
let {itemId, page} = req.body;
if (token == null){
res.json({status: 'error', error: 'wrong token'});
}
try {
let userVerification = jwt.verify(token, JWT_SECRET);
let _id = userVerification.id;
let item = await Item.findById(itemId);
await User.updateOne({_id},{
$set: {
lastViewed: [
{
title: item.title,
page: page
}
]
}
},
{ upsert: true }).catch(err => console.log(err));
res.json({status: 'ok' });
} catch(err){
res.json({status: 'error', error: 'wrong token'});
}
});
What do you think I should do你觉得我应该怎么做
You point out the element you want to update rather than point to the whole array.您指出要更新的元素而不是指向整个数组。 The
$
operator is used to identify the array element you want to update. $
运算符用于标识要更新的数组元素。 Look at the documentation 查看文档
You can write the update query by您可以通过以下方式编写更新查询
User.update({
"_id": mongoose.Types.ObjectId(_id),
"lastViewed.title": "n3"
},
{
$set: {
"lastViewed.$.page": 4
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.