简体   繁体   中英

MongoDB/Mongoose: Updating entire document with findOneAndUpdate()

I want to use the findOneAndUpdate() method to either create a document if it doesn't exist, or update it if does exist. Consider the following code:

SampleComment = new Comment({
    id: '00000001',
    name: 'My Sample Comment',
    ...
})

This is my attempt to find out if SampleComment aldready exists, and if so, update it, otherwise creating it:

Comment.findOneAndUpdate(
    { id: SampleComment.id }, 
    { SampleComment }, // <- NOT PASSING THE OBJECT
    { upsert: true, setDefaultsOnInsert: true }, 
    function(error, result) {
        ...
});

I'm trying to pass the Model-instance as an object in the second argument, but result is only returning the default values of the model. Same goes for the document itself.

How do I pass the entire object SampleComment correctly in the second argument?

What's actually happening when you're calling findOneAndUpdate() with your Document object as your update object with { SampleComment } is you're destructuring that to be SampleComment : {...} .

Mongoose will then go and look at your database document for any property named SampleComment , find none, and then do nothing. Returning to you a document where nothing would have changed.

What you can do to fix this is convert your Document back to a plain update object first with Mongoose's toObject() method, remove the _id (since that property is immutable and you don't want to replace it anyway with an update) and then save it with your existing findOneAndUpdate() method. eg:

let newComment = SampleComment.toObject();
delete newComment._id;

Comment.findOneAndUpdate(
    { id: SampleComment.id }, 
    newComment,
    { upsert: true, setDefaultsOnInsert: true }, 
    function(error, result) {
        ...
    }
);

You can then see the updated document in your database. To receive the updated document in your result you need to also pass the option { new: true } to your options object.

Here's the link to Mongoose's toObject() Document method documentation.

By default the returned result is going to be the unaltered document. If you want the new, updated document to be returned you have to pass an additional argument named new with the value true .

Comment.findOneAndUpdate({id: SampleComment.id}, SampleComment, {new: true, upsert: true, setDefaultsOnInsert: true}, function(error, result) {
    if(error){
        console.log("Something wrong when updating data!");
    }

    console.log(result);
});

See http://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate :

function(error, doc) {
  // error: any errors that occurred
  // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
}

I found the way to make it easy and fast :D

In my case I Just needed to insert the object from a form and update the doc. Maybe that helps someone:

Angularjs Controller:

  $scope.bike ={};
  fBikeFactory.get({
        id:$stateParams.id
      })
      .$promise.then(function (response) {
        $scope.bike = response;
      },function (response) {
        $scope.bike = "Error: " + response.status + " " + response.statusText;
      });


// UPDATE a BIKE
      $scope.saveBike = function() {
        $scope.processing = true;

        var updateQuery = fBikeFactory.update({id: $stateParams.id}, $scope.bike);
        updateQuery.$promise.then(function(rep) {
            $scope.processing = false;
            $scope.message = "Desat amb èxit";
            setTimeout(function(){ $state.go('home.adminBikes');$scope.bike.message = ''; }, 750);
        },function(err) {
            $scope.processing = false;
            $scope.message = 'Error al Desar, torna a provar-ho.';
        })
      };

Require the model:

var Bike = require('../models/bikeModel.js');

...

ROUTE:

bikesRouter.route('/bikes/:id')
    .put(function(req,res) {


    Bike.findOneAndUpdate(
            {_id: req.params.id}, // find a document with that filter
            req.body, // document to insert 
            {upsert: true, new: true, runValidators: true}, // options
            function (err, updatedBike) { // callback
                if (err) console.log('ERROR '+ err);
                else res.json(updatedBike)

            }
        );
    });

Hope that helps :D

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