Reputation: 15
I want to merge my collection by updating a number field and an array.
This is my schema mongodb :
{
url: String,
email: [String],
vote: Number
}
node.js code :
like = _.merge(like, req.body);
like.save(function (err) {
if (err) { return handleError(res, err); }
});
this code updates the vote field by incrementing a value, but replaces the existing email whereas I want to push the email into the array.
I want to increment vote value, and push email into an array, like ["[email protected]", "[email protected]",... ]
etc.
I don't know how to do that.
Upvotes: 0
Views: 904
Reputation: 15
I combined @Nindaff's solution with the push method, this solution worked for me :
like.vote = (like.vote, req.body.vote);
like.email.push(req.body.email);
like.save(function (err) {
if (err) { return handleError(res, err); }
});
Upvotes: 0
Reputation: 103445
Use _.assign()
instead which works in a way that for each property in source, it copies its value as-is to destination. If property values themselves are objects, there is no recursive traversal of their properties. Entire object would be taken from source and set in to destination. The following examples demonstrate the differences between _.assign()
and _.merge()
:
var dest = {
p: { x: 10, y: 20},
};
var src = {
p: { x: 20, z: 30},
};
console.log(_.merge(dest, src));
Output
[object Object] {
p: [object Object] {
x: 20,
y: 20,
z: 30
}
}
console.log(_.assign(dest, src));
Output
[object Object] {
p: [object Object] {
x: 20,
z: 30
}
}
So your final code should look like:
like = _.assign(like, req.body);
like.save(function (err) {
if (err) { return handleError(res, err); }
});
Upvotes: 2
Reputation: 2214
With mongoose docs you can modify the document like any other object in javascript. Your vote was not getting incremented most likely because req.body.vote
was the same value as like.vote
, couldn't know for sure with out knowing the incoming data. But the following solution will increment the vote and _.merge
the email
property.
// for just modifing the email property
like.email = _.merge(like.email, req.body.email);
// increment the vote like you would with any number in JavaScript
like.vote++;
like.save(function(err) {
if (err) retuurn handleError(res, err);
// handle successfull save
});
Upvotes: 0