Increment value in update query mongoDB - javascript

I am trying to add two values in a mongoose function.
This the function im using:
Equipa.findOne({ '_id': req.params.equipaID }, function (error, equipa) {
if (error) {
return (error);
}
if (util.isNullOrUndefined(equipa)) {
return res.status(204).end()
}
console.log(equipa.distanciaTotal + "------" + req.body.distanciaPercorrida),
{ total : {$add[equipa.distanciaTotal,req.body.distanciaPercorrida]}},
console.log(total)
});
The values in equipa.distanciaTotal and req.body.distanciaPercorrida are correct, and so is the Equipa found by Equipa.findOne.
I think it will be fine updating the document, but I simply cannot add the two values.

You can use $inc to increment the existing value
Equipa.findOneAndUpdate(
{ '_id': req.params.equipaID },
{ '$inc': {
distanciaTotal: req.body.distanciaPercorrida }
}
)

You could either use $inc
Equipa.findOneAndUpdate(
{ '_id': req.params.equipaID },
{ $inc: { distanciaTotal: req.body.distanciaPercorrida } }
);
Or save the document after updating it
Equipa.findOne({ '_id': req.params.equipaID }, (err, equipa) => {
equipa.distanciaTotal += req.body.distanciaPercorrida;
equipa.save();
});

Related

Update mongo collection with values from a javascript map

I have a collection that looks like this
[
{
"project":"example1",
"stores":[
{
"id":"10"
"name":"aa",
"members":2
}
]
},
{
"project":"example2",
"stores":[
{
"id":"14"
"name":"bb",
"members":13
},
{
"id":"15"
"name":"cc",
"members":9
}
]
}
]
I would like to update the field members of the stores array taking getting the new values from a Map like for example this one
0:{"10" => 201}
1:{"15" => 179}
The expected result is:
[
{
"_id":"61",
"stores":[
{
"id":"10"
"name":"aa",
"members":201
}
]
},
{
"_id":"62",
"stores":[
{
"id":"14"
"name":"bb",
"members":13
},
{
"id":"15"
"name":"cc",
"members":179
}
]
}
]
What are the options to achieve this using javascript/typescript?
In the end, I resolved by updating the original database entity object with the values in the map, then I have generated a bulk query.
for (let p of projects) {
for(let s of p.stores) {
if(storeUserCount.has(s.id)){
s.members = storeUserCount.get(s.id);
}
};
bulkQueryList.push({
updateOne: {
"filter": { "_id": p._id },
"update": { "$set": {"stores": p.stores} }
}});
};
await myMongooseProjectEntity.bulkWrite(bulkQueryList);
You can use update() function of Mongoes model to update your expected document.
Try following one:
const keyValArray= [{"10": 201},{"15":"179"}];
db.collectionName.update({_id: givenId},
{ $push: { "stores": {$each: keyValArray} }},
function(err, result) {
if(err) {
// return error
}
//return success
}
});

Remove Object from Array MongoDB

I need to remove a specific object from my mongoDB array.
Should remove the info above inside the red cube but (0: Object)
I tried the way I show below but didn't work.
And I need to remove the entire object but can't pass the values directly in the query so I need to grab the info from mongoDB and remove them.
router.post("/deleteArquive/:id", ensureAuthenticated, (req, res) => {
var id = mongoose.Types.ObjectId(req.params.id);
House.update(
{ "expensesHouse._id": id },
{
$pull: {
expensesHouse: {
status: "expensesHouse.status",
_id: "expensesHouse._id",
expenseType: "expensesHouse.expenseType"
}
}
}
).then(house => {
if (house.userID !== req.user.id) {
res.redirect("/houses/houses");
} else {
req.flash("success_msg", "House removed!");
res.redirect("/houses/houses");
}
});
});
If I understand the requirements correctly, this should do the job:
House.update(
{ "expensesHouse._id": id },
{
$pull: {
expensesHouse: {
_id: id
}
}
}
)

mongoose/javascript: Can't update collection in Mongodb

This is my db schema
let couponId = Schema({
RestaurantId: { type: String },
RestaurantName: { type: String },
RestaurantLocation: { type: String },
AssignedTo: Schema.Types.Mixed,
CouponValue: { type: [String] }
});
I want to update the AssignedTo field with a value of array of objects with a dynamic key and a value. I am performing this query
CouponId.findOne({
"RestaurantId": resId
}, (err, restaurant) => {
value.push({
[userNumber]: restaurant.CouponValue[0]
});
console.log(value);
restaurant.update({
"RestaurantId": resId
}, {
$set: {
"AssignedTo": value
}
}, function(err) {
if (err) {
console.log(err);
} else {
console.log("updated");
}
});
});
The query, when executed, is giving the result of updated in console but its not getting updated in db. If this query is converted to MongoShell query and executed, it gives the result and collection is getting updated, where mongoShell query i am running is
db.couponids.update({"RestaurantId" : "1234"},{$set:{"AssignedTo":[{"1234":"2345"}]}});
Where am i going wrong?
restaurant is the output from the first collection and doesn't have any update function in it... So, You need to keep the same collection name from which you have done findOne
CouponId.update({
"RestaurantId": resId
}, {
$set: {
"AssignedTo": value
}
}, function(err) {
if (err) {
console.log(err);
} else {
console.log("updated");
}
});

How to append a data to an object property in mongodb

I want to send request to a mongodb database.
For example I have this object:
{
id:"1",
requestType : {
"api1" : {count:12,firstTime:12},
"api2" : {count:6,firstTime:18}
}
}
after getting data by "id" I want to append another row to "requestType" for example "api3":{count:56,firstTime:11}.
my expected object is:
{
id:"1",
requestType : {
"api1" : {count:12,firstTime:12},
"api2" : {count:6,firstTime:18},
"api3":{count:56,firstTime:11}
}
}
currently I'm using this query by mongoose:
apiAttemptsModel.findOneAndUpdate(query, {
$set: {
requestType : {"api3":{count:56,firstTime:11}}
}
}, {upsert: true, new: true}, function (err, row) {
if (err) {
callback('err is ' + err)
} else {
callback(row);
}
});
But this code will exchange old requestType object with the new one.
Try this:
apiAttemptsModel.findOneAndUpdate(query, {
$set: {
"requestType.api3" : {count:56, firstTime:11}
}
}, {upsert: true, new: true}, function (err, row) {
if (err) {
callback('err is ' + err)
} else {
callback(row);
}
});
By the way, this is not the proper way to use callbacks.
callbacks in node are usually called with the following signature:
function(error, data) -
thus when calling callback(row); a user of this method might expect an error there, much like you did with the callback function on line 5.
The first argument is usually null when no error has occurred.
In addition, calling callback('err is ' + err) will only keep the error's message and discard its stack trace, because the error is "converted" to a string.
I'd convert your code to:
apiAttemptsModel.findOneAndUpdate(query, {
$set: {
"requestType.api3" : {count:56, firstTime:11}
}
}, {upsert: true, new: true}, function (err, row) {
if (err) {
callback(err)
} else {
callback(null, row);
}
});
Set upset to false. This will update the document, but will not create it if it does not already exist.
https://docs.mongodb.com/manual/reference/method/db.collection.update/

JS: $addToSet or $pull depending on existing/missing value

I need to add or remove an ID from an array (target), depending if it is already existing. This is how I am doing this:
var isExisting = Articles.findOne({ _id }).target.indexOf(mID) > -1
if (isExisting === false) {
Articles.update(
{ _id },
{ $addToSet: { target: mID } }
)
} else if (isExisting === true) {
Articles.update(
{ _id },
{ $pull: { target: mID } }
)
}
Is it possible to do this in a better way - without doing if/else and min. two db operations?
Mongoose operations are asynchronous, so you need to wait for its callback to get the document.
// find the article by its ID
Articles.findById(_id, function (err, article) {
// make appropriate change depending on whether mID exist in the article's target
if (article.target.indexOf(mID) > -1)
article.target.pull(mID)
else
article.target.push(mID)
// commit the change
article.save(function (err) {
});
})
Although you are doing if/else, you are doing 2 operations.
here is my suggestion
let isExisting = Articles.findOne({ _id: _id, target : mID}) //mongo can search for mID in array of [mIDs]
let query = { _id : _id };
let update = isExisting ? { $pull: { target: mID } } : { $addToSet: { target: mID } };
Articles.update(query, update);
is it better and clearer now?

Categories

Resources