Partial update of a subdocument with nodejs/mongoose

后端 未结 4 1968
情话喂你
情话喂你 2020-12-08 08:36

Is it possible to set multiple properties on a (sub)document in one go with Mongoose? An example of what I\'m trying to do:

Let\'s say I have this schema:

         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-08 09:15

    I've done different, in a REST application.

    First, I have this route:

    router.put('/:id/:resource/:resourceId', function(req, res, next) {
        // this method is only for Array of resources.
        updateSet(req.params.id, req.params.resource, req, res, next);
    });
    

    and the updateSet() method

    function updateSet(id, resource, req, res, next) {
        var data = req.body;
        var resourceId = req.params.resourceId;
    
        Collection.findById(id, function(err, collection) {
            if (err) {
                rest.response(req, res, err);
            } else {
                var subdoc = collection[resource].id(resourceId);
    
                // set the data for each key
                _.each(data, function(d, k) {
                  subdoc[k] = d;
                });
    
                collection.save(function (err, docs) {
                  rest.response(req, res, err, docs);
                });
            }
        });
    }
    

    The brilliant part is mongoose will validate the data if you define the Schema for this subdocument. This code will be valid for any resource of the document that is an Array. I'm not showing all my data for simplicity, but is a good practice to check for this situations and handle the response error properly.

提交回复
热议问题