简体   繁体   English

findOneAndUpdate数组中的嵌套对象

[英]findOneAndUpdate nested object in array

Trying to use findOneAndUpdate() to change an object inside an array within MongoDB. 尝试使用findOneAndUpdate()来更改MongoDB中数组内的对象。 The documentation for mongoDB's nodeJS driver isn't clear to me. mongoDB的nodeJS驱动程序的文档对我来说并不清楚。 The document looks like this: 该文件如下:

{
  _id:ObjectID(),
  some: string,
  body: string,
  steps:[
   [0]{name: "foo", state:"Q"},
   [1]{name: "bar", state:"Q"},
   [n]{name: "fooBar", state:"Q"}
 ]
}

I need to lookup the steps name (foo) and set it's state to P (for in progress) and then to C (for complete) when the task has been executed or E when it errors. 我需要查找步骤名称(foo)并将其状态设置为P(正在进行中),然后在执行任务时将其设置为C(完成)或在错误时将其设置为E.

I'll then need to also grab the name of the next step to. 然后我还需要抓住下一步的名称。

Finding the document isn't hard as I will have the _id already, it's the update portion that's getting me. 找到文档并不难,因为我已经有了_id,这是我的更新部分。

EDIT: This is what I've got so far 编辑:这是我到目前为止所得到的

  async msg => {
    const _id = msg.content.toString();
    const id = new objectId(_id);
    logger.info(`${name} consumer - Recieved new task, fetching details`, {
      id
    });
    try {
      const jobDetails = await collection.findOneAndUpdate(
        { _id: id },
        {
          /**/
        }
      );
      await consumer.task(jobDetails);
    } catch (e) {}
  },

It's the framework for a rabbitMQ consumer 它是rabbitMQ消费者的框架

I don't know how would you choose wich letter to set - P, C or E, because it is not quite clear, but for replacing a value in mongoDB it would look like this (let's say for 'P'): 我不知道你会如何选择设置的字母--P,C或E,因为它不太清楚,但是为了替换mongoDB中的值,它看起来像这样(让我们说'P'):

myCollection.findOneAndUpdate({"_id": docId, "steps.name": "foo"},
    {$set: {"steps.$.state": "P"}})
  1. Find the document you need to change. 找到您需要更改的文档。
  2. Find the object inside the array "steps.name": "foo" . 在数组"steps.name": "foo"找到对象"steps.name": "foo" And you get the position of that object in array. 然后你得到该对象在数组中的位置。
  3. You're setting new value for the object's property ( $ reflects the position). 您正在为对象的属性设置新值( $反映位置)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM