Javascript 无法更新文档';s属性值,该属性值位于Mongoose中的对象数组中
所以我正在开发这个应用程序,我需要更新一个文档。文档由一系列对象组成。因此,我需要更新其中一个对象中的属性值,但在更新之前,我需要根据数组索引找到正确的对象Javascript 无法更新文档';s属性值,该属性值位于Mongoose中的对象数组中,javascript,node.js,mongodb,express,mongoose,Javascript,Node.js,Mongodb,Express,Mongoose,所以我正在开发这个应用程序,我需要更新一个文档。文档由一系列对象组成。因此,我需要更新其中一个对象中的属性值,但在更新之前,我需要根据数组索引找到正确的对象 async function updatePost (post) { const pendingPostIndex = post.postContent.findIndex( item => { return item.status === "pending"; });
async function updatePost (post) {
const pendingPostIndex = post.postContent.findIndex( item => {
return item.status === "pending";
});
const update = {
pid: 0,
postContent[pendingPostIndex].status: "completed"
}
await Post.findOneAndUpdate({ _id: post._id }, update);
}
当我必须更新特定帖子时,会调用上面的函数。参数post
是我必须更新的文档
然后,我正在查找待处理帖子的索引
,以便使用该索引将待处理状态更新为complete
,并将pid
值更新为0。显然,像这样更新pid
值是可行的。但不是第二个
上面的代码在上面的update
对象的第二个属性下面加上红色下划线,显示VS代码中的错误
终端显示SyntaxError:Unexpected token'['
数据如下所示:
{
"pid" : 4927fn380m38jc5,
"postContent" : [
{
"status" : "pending",
"text" : "post 1",
"image" : ""
},
{
"status" : "complete",
"text" : "post 2",
"image" : ""
},
{
"status" : "pending",
"text" : "post 3",
"image" : ""
}
],
}
首先,以下语法在对象内部是完全错误的:
postContent[pendingPostIndex].status: "completed"
其次,如果您只想更新pid和状态,为什么不:
const update = {
pid: 0,
status: "completed"
}
await Post.findOneAndUpdate({ _id: post._id }, update);
根据评论进行编辑:
如果只想更新数组中处于挂起状态的特定索引处的子文档。
你只需要:
const statusKeyUpdate = "postContent."+ pendingPostIndex +".status";
Post.findOneAndUpdate(
{ _id: post._id, "postContent.status": "pending" },
{ $set: { "pid":0, [statusKeyUpdate]:"completed" } }
)
我想通过使用索引查找数组子文档中的特定对象来更新它(如果可能的话).在我的数据中,没有一个文档名为
status
,正如您所提到的。2件事:首先,这不会用挂起的值更新所有状态吗?其次,pid
不在postContent数组子文档中。它是独立的。谢谢您的时间。如果您想更新索引中的元素,您可以在$set$set:{'pid':0,“postContent.”+pendingPostIndex+“.status:“completed”}
再次更新答案。希望这有帮助!