简体   繁体   中英

How to update nested objects in MongoDb with Mongoose

I am trying to update one key value in a nested object in MongoDB. currently, the way I am doing it the entire nested object is being overwritten, how can I change one key-value pair?

  try {
      Files.updateOne(
        { _id: document._id },
        {a:{b:{c:"new text", d: "not to change"}}},
        function (err, result) {
          if (err) {
            res.send(err);
          } else {
            res.send(result);
          }
        }
      );
    } catch (err) {
      res.status(400).send(err);
    }

Try this:

try {
  Files.updateOne(
    { _id: document._id },
    { "a.b.c": "new text" },
    function (err, result) {
      if (err) {
        res.send(err);
      } else {
        res.send(result);
      }
    }
  );
} catch (err) {
  res.status(400).send(err);
}

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