admin管理员组文章数量:1242887
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?
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?
3 Answers
Reset to default 7What'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./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
本文标签: javascriptMongoDBMongoose Updating entire document with findOneAndUpdate()Stack Overflow
版权声明:本文标题:javascript - MongoDBMongoose: Updating entire document with findOneAndUpdate() - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740149269a2232354.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论