简体   繁体   中英

Unable to update data values on mongoDb native findOneAndUpdate query

exports.update_activity_status = (req, res) => {
  const {
    campaign_id,
    leadId,
    leadActivity,
    status,
  } = req.body;

  const client = mongoClient.connect(`${process.env.MONGO_URL}`, {
    useUnifiedTopology: true,
  });
  client.then((cli) => {
    cli
      .db(`${process.env.DATABASE_NAME}`)
      .collection(`${process.env.ACTIVITY_COLLECTION}`)
      .findOneAndUpdate(
        {
          "data.campaign_id": mongoose.Types.ObjectId(campaign_id),
          "data.leads.$._id": mongoose.Types.ObjectId(leadId),
          // "data.leads._id" : leadId
        },
        {
          $set: {
            "data.leads.$.leadActivity": leadActivity,
            "data.leads.$.status": status,
          },
        },
        {
          returnNewDocument: true,
        }
      )
      .then((result) => {
        console.log("UPDATED RESULT", result);
        res.json(result)
      })
      .catch((err) => console.log("new err", err));
  });
};

In my query, I need to update the status and leadActivity of the users whose leadId matches the following conditions:

  1. campaign_id that matches the document (this is working fine).
  2. leadsId that matches inside that particular document (not working).

First I tried using only db.find({"data.campaign_id": mongoose.Types.ObjectId(campaign_id)}) and it returns me the data that matches only the first condition as specified above. As soon as I try it along with second condition and findOneAndUpdate({....}) , accessing the nested data after including secondary filter condition returns null .

Here's is what my document object looks like:

在此处输入图像描述 Any help to resolve this is appreciated. Thanks in advance.

The second condition for matching the _id in the leads -array is incorrect, you need to change it to:

  "data.leads._id": mongoose.Types.ObjectId(leadId)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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