Remove Object from Array MongoDB - javascript

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
}
}
}
)

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
}
});

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");
}
});

Increment value in update query mongoDB

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();
});

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?

Update element from user profile in Meteor

I am trying to update firstName field created in user.profile using onCreateUser:
Accounts.onCreateUser(function(options, user) {
user.profile = options.profile || {};
user.profile.firstName = options.firstName;
return user;
});
Also I use allow:
Meteor.users.allow({
update: function(userId, doc, fields, modifier) {
if (fields === "profile.firstName") {
return true;
}
}
});
When I use:
Meteor.users.update({
_id: Meteor.userId()
}, {
$set: {
profile: "George"
}
});
It works but it is not what I need.
What I need is to update firstName:
Meteor.users.update({
_id: Meteor.userId()
}, {
$set: {
profile.firstName: "George"
}
});
But I get this error:
SyntaxError: missing : after property id
What am I missing?
If you are using the dot notation you need to enclose the whole dotted field name in quotes.
In your case:
Meteor.users.update({
_id: Meteor.userId()
}, {
$set: {
"profile.firstName": "George"
}
});
Read more about updating an embedded field.

Categories

Resources