How to update array with Meteor [duplicate] - mongodb

This question already has answers here:
Push items into mongo array via mongoose
(11 answers)
Closed 4 years ago.
I'm trying to add an element in an array but can't figure out what is causing my problem,
Don't know if i have to do an insert or an update anyway tried both, both not working
addUserToArray:function(userId,_id,email){
check(_id, String)
check(userId,String)
check(email, String)
var current_test = Modules.test.checkTestExist(test_id);
const USER = Accounts.findUserByEmail(email)
let test=USER._id
if(userId==current_test.senders[0]){
Tests.update(_id, {$set: {'name': name}}) // this one getting updated
Tests.update(test_id, { $set: { "current_test.senders": test} }) // this is not working
}
i got the error
UserIds that can send messages on this test must be an array",

You just need to change the $set by $push
Tests.update(box_id, { "$push": { "current_test.senders": USER._id} })

Related

Update a mongodb document and get the updated document [duplicate]

This question already has answers here:
Update And Return Document In Mongodb
(7 answers)
Mongoose: findOneAndUpdate doesn't return updated document
(16 answers)
Closed 3 years ago.
Using Express and MongoDB, how can I update a document, then get that updated document?
The following code will find the profile document with the given user.id, then remove the experience with the given exp_id from the experience array. However, it returns the original profile (including the removed experience), not the updated one.
let profile = await Profile.findOneAndUpdate(
{ user: req.user.id },
{ $pull: { experience: { _id: req.params.exp_id } } },
{ returnNewDocument: true }
)
console.log(profile); // logs the original profile, still incl the removed experience
What do I need to change for it to return the updated profile?
Docs: https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/

updating multiple documents by passing a list objectids to findByIdAndUpdate [duplicate]

This question already has answers here:
MongoDB: How to update multiple documents with a single command?
(13 answers)
FindAndModify, return array of Objects
(1 answer)
Closed 5 years ago.
I am trying to use mongoose's findByIdAndUpdate method to pass in a list of object id's and updating them at once. However, I am getting a "Error: Can't use $set with ObjectId." error which I can't seem to associate with my code.
Here's my code.
return ComponentModel.findByIdAndUpdate({
_id: {
$in: input.subjectIds
},
$set: { location: input.newLocation }
}).then(res => res);
findByIdAndUpdate is for one document. For multiple documents you can use update with multi flag true.
return ComponentModel.update(
{_id: {$in: input.subjectIds}},
{$set: {location: input.newLocation}},
{"multi": true}
).then(res => res);

MongoDB : Add field in each array elements [duplicate]

This question already has answers here:
How to Update Multiple Array Elements in mongodb
(16 answers)
Closed 5 years ago.
I'm starting with mongoDB and I want to update a nested array in my documents to add some initial value, but I can't find a way to do it with mong.
here is my document :
{
"_id":"cTZDL7WThChSvsvBT",
"name":"abc",
"players":[
{
"playerName":"Name1"
},
{
"playerName":"Name2"
}
]
}
What I want to do :
{
"_id":"cTZDL7WThChSvsvBT",
"name":"abc",
"players":[
{
"playerName":"Name1",
"NewField1":0,
"NewField2":0
},
{
"playerName":"Name2",
"NewField1":0,
"NewField2":0
}
]
}
Does anyone have a solution for this kind of situation?
This adds the new fields to the player array ...
db.collection.update({_id: 'cTZDL7WThChSvsvBT', players: {$exists: true}}, {$set: {'players.$.NewFieldOne': 0, 'players.$.NewFieldTwo': 0}})
... but since Mongo will only update the first element of an array which matches the query you are a bit stuffed. You can, of course, choose which array element to update by using the positional operator (as in my example) or by choosing a specific element (as the previous poster suggested) but until Mongo supports 'array updates' on all elements I think you're left with a solution such as: find the relevant documents and then update each one (i.e. a client side update solution).
I finally found a way by editing directly the document in JS like this :
db.doc.find({_id: myDocId}).forEach(function (channel) {
channel.players.forEach(function (player) {
player.newField1 = 0;
player.newField2 = 0;
});
db.doc.update({_id: myDocId}, channel);
});
considering you want to update an element which is an object also,
how about this?
db.collections.updateOne({_id: "cTZDL7WThChSvsvBT"}, {$set: {"players.0.NewField1": 0, "players.0.NewField2: 0}});

Search Specific Element In array mongodb [duplicate]

This question already has answers here:
How to filter array in subdocument with MongoDB [duplicate]
(3 answers)
Closed 6 years ago.
I am trying to find a specific object from array of objects in mongodb.
I am trying this
Company.findOne ({
"configuration.macAddress": "AB-90-dF-8d"
});
It returns me the exact company but it returns all the configuration array
I want only configuration with matching macAddress
Instead use aggregate(). $unwind the configuration array first, then you can $match the specific element only.
Company.aggregate([
{
"$unwind": "$configuration"
},
{
"$match":{
"configuration.macAddress": "AB-90-dF-8d"
}
}
]);
you can use $elemMatch to find a particular object in an array.
Company.find({ configuration: { $elemMatch: { macAddress: "AB-90-dF-8d"} } } );
can you show me your array of objects?

How to do update the matched array element [duplicate]

This question already has answers here:
Update field in exact element array in MongoDB
(5 answers)
Closed 6 years ago.
user1 in database
{
counts: [{code:"aaa", num:100}, {code:"bbb", num:200}]
}
counts is an Array, it has two elements code and num.
How to let num increase 1 if code = "aaa"?
Meteor.users.update(user1._id, {$inc: {???}}); // How to write this?
Thanks
Gotta positionally match. Example:
Players.update({
_id: Meteor.userId(),
'games._id': Session.get('gameId')
}, {
$inc: { 'games.$.score': 1 }
});