I
I
iGarett2016-07-13 12:15:36
MongoDB
iGarett, 2016-07-13 12:15:36

How to update an array of nested documents in MongoDB?

Please tell me how to correctly execute the request so that all the isDeleted fields in the image array and the isDeleted field of the Category are updated.
MongoDB + Mongoose
Category:

{
    "_id": "5785c3e2b40e6ba6a908775e",
    "category_title": "Светлое фентези",
    "category_image_url": "category_2342734.png",
    "design_url": "desing_2.png",
    "__v": 3,

    "image": [
      {
        "_id": "5786042e4854e51ef0b8106c",
        "image_title":"Лесной дракон"
        "image_url": "image.png",
        "isDeleted": false
      },
      {
        "_id": "578600983502e51ef0b810cd",
        "image_title":"Горный дракон",
        "image_url": "image.png",
        "isDeleted": false
      },
      {
        "_id": "20934029580294df1230a89",
        "image_title":"Золотой дракон",
        "image_url": "image.png",
        "isDeleted": false
      }
    ],

    "isDeleted": true
  },

function deleteCategory(req, res, next) {
    model.CategoryModel.findByIdAndUpdate(req.params.id, { isDeleted: true }, function(err, category) {
        if (err) return next(err);
        res.json({ message: "Категория успешно удалена" });
    });
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2016-07-13
@iGarett

function deleteCategory(req, res, next) {
    model.CategoryModel.findByIdAndUpdate(req.params.id, { isDeleted: true }, function(err, category) {
        if (err) return next(err);

        category.image.forEach(item => {
          item.isDeleted = true
        })

        category.isDeleted = true/false // что вам тут нужно

        category.markModified('image') //http://mongoosejs.com/docs/faq.html

        model.CategoryModel.save((err, updatedItem) => {
          if (err) {
            return res.status(400).json({ message: err.message })
          } else {
            return res.json({ message: "Категория успешно удалена" })
          }
        })
    });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question