Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 无法更新文档';s属性值,该属性值位于Mongoose中的对象数组中_Javascript_Node.js_Mongodb_Express_Mongoose - Fatal编程技术网

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“postContent.”+pendingPostIndex+“.status”。如果pid是单独的
$set:{'pid':0,“postContent.”+pendingPostIndex+“.status:“completed”}
再次更新答案。希望这有帮助!