mongoDB - $push _id to specific users - javascript

I want to push an _id to specific users, but unfortunately it does not work as expected.
Here is my code:
var chatId = Chat.insert(privateMessage);
Users.update({_id: {$in: participants}}, {$push: {chat: chatId}});
I want to push the chatId to all users within the participants array.
The participants array looks like this: [ '3JsJP8MJZXRdACJqs', 'En2mTYgRj3BkHc6AW', 'p3kgiZbjYpvvYAWYs' ]. After checking the result, I noticed that only the user with the _id: 3JsJP8MJZXRdACJqs had the chatId in the document.
Any help would be greatly appreciated.

By default, the update() method updates a single document. To update multiple documents, use the multi option in the update() method.
as:
Users.update({
_id : {
$in : participants
}
}, {
$push : {
chat : chatId
}
},
{multi : true}
);
Refer: http://docs.mongodb.org/manual/tutorial/modify-documents/#update-multiple-documents

Related

Update mongoDB updating in forEach not working

I have a Node backend server, connected to a MongoDB database. Here I have a patients collections containing patients object. I'm trying to update an attribute called position on each object.
I have started by retrieving the documents from MongoDB:
const patientsToChange = await Patient.find()
Then I'm trying to update some attributes in the array by iteration over the array.
patientsToChange.forEach(function (patient) {
patient.queuePosition = parseInt(patient.queuePosition) + 1
console.log(patient._id)
let updatedPatient = patient.update({ _id: patient._id }, patient)
})
What am I missing here?
Is it even possible to update in a forEach loop?
instead of patient.update you should use Patient.update. Also it is better to use $inc for incrementing one field:
Patient.updateOne({ _id: patient._id }, { $inc: { queuePosition }} )

Mongoose: Add more items to existing object

Using Mongoose, How can I add more items to an object without replacing existing ones?
User.findOneAndUpdate(
{ userId: 0 },
{ userObjects: { newItem: value } }
);
The problem with above code is that it clears whatever was there before and replaces it with newItem when I wanted it just to add another item to userObjects(Like push function for javascript arrays).
Use dot notation to specify the field to update/add particular fields in an embedded document.
User.findOneAndUpdate(
{ userId: 0 },
{ "userObjects.newerItem": newervalue } }
);
or
User.findOneAndUpdate(
{ userId: 0 },
{ "$set":{"userObjects.newerItem": newervalue } }
);
or Use $mergeObjects aggregation operator to update the existing obj by passing new objects
User.findOneAndUpdate(
{"userId":0},
[{"$set":{
"userObjects":{
"$mergeObjects":[
"$userObjects",
{"newerItem":"newervalue","newestItem":"newestvalue"}
]
}
}}]
)
According to your question, i am guessing userObjects is an array.
You can try $push to insert items into the array.
User.findOneAndUpdate(
{ userId: 0 },
{ $push : {"userObjects": { newItem: value } }},
{safe :true , upsert : true},function(err,model)
{
...
});
For more info, read MongoDB $push reference.
Hope it helps you. If you had provided the schema, i could have helped better.
Just create new collection called UserObjects and do something like this.
UserObject.Insert({ userId: 0, newItem: value }, function(err,newObject){
});
Whenever you want to get these user objects from a user then you can do it using monogoose's query population to populate parent objects with related data in other collections. If not, then your best bet is to just make the userObjects an array.

Unable to push data into current object inside mongo database

I am using mongodb native and Node.js 6.5.0.
I have user object in mongodb which is structured as:
{
"_id" : ObjectId("57d7d294d96a73d128c46db9"),
"id" : "105862592064",
"labels" : [
]
}
I have a loop (for each user found) get data from API and then push it into object attribute of array type. Where user id user.id and data to push is resp.labels.
This is my code:
db.collection('users').update(
{"id":user.id},
{"$push":{"users.labels":resp.labels}}
)
It doesn't return any error, neither it does update objects. What have I done wrong?
Try this:
db.collection('users').update(
{"id":user.id},,
{
$push: {
labels: {
$each: //yourArray
}
}
}
);
$push is for pushing a single element to an array. Use $push together with $each to push multiple elements. Also, quotes around the object labels should not be neccessary:
db.collection('users').update(
{ id:user.id },
{ $push: { labels: { $each: resp.labels } } }
)
Try $set
db.collection('users').update(
{"id":user.id},
{$set:{"users.labels":"hola"}})
Try to include {upsert:true}:
db.collection('users').update(
{"id":user.id},
{"$push":{"users.labels":resp.labels}},
{"upsert": true}
);
Upsert inserts new value if it doesn't already exists.

Finding nested array data with elemMatch in MongoDB/Meteor

collection structure as such:
{"_id" : "abc",
"potentialUsers" : [{"userID" : "def"},
{"userID" : "ghi"}]
},
{"_id" : "123",
"potentialUsers" : [{"userID" : "456"},
{"userID" : "789"}]
},
I want to query if user abc has the user def in their potential users array. My current query (client) is
getPendingLiftRequests: function() {
return collection.find({}, {potentialUsers: {$elemMatch: {userID: Meteor.user().services.facebook.id}}});
}
On the server I publish all of that collection to the user, and then just selectively show it based on the view of the client. However, when I try to use an elemMatch on the array, it just shows all of the records, when it should only show 1.
You don't need $elemMatch here. This should work:
var fId = Meteor.user().services.facebook.id;
return collection.find({'potentialUsers.userID': fid});
Have look at the documentation for minimongo in Meteor:
http://docs.meteor.com/#/full/find
You have to use the fields option to get the desired result.
getPendingLiftRequests: function() {
return collection.find({}, { fields: { potentialUsers: {$elemMatch: {userID: Meteor.user().services.facebook.id}}}});
}

Mongodb: Find ids $in nested array property

I have the following data structure for my users in my mongodb:
{
_id: "someId",
profile: {
username: "oliv",
friendRequests: [
{ fromUserId: "anId", accepted: false, created: "someDate"},
{ fromUserId: "otherId", accepted: true, created: "otherDate"}
]
}
I'd like to retrieve the user objects that are referenced in my logged user's friendsRequested.
So I tried something like this:
Meteor.users.find({_id: {$in: Meteor.user().profile.friendRequests.fromUserId}});
// FYI: Meteor.users is the collection and Meteor.user() retrieves the current user
But it's not working. I'm assuming it's because of the nested array.
Is there any way of telling mongo to iterate through the fromUserId or something?
Thanks
Change your query to:
Meteor.users.find({_id: {$in: _.pluck(Meteor.user().profile.friendRequests, 'fromUserId') }});
Reasoning:
friendRequests is an array of objects, and $in wants an array of strings(the ids), using _.pluck you're able to pass an array of objects, and tell _ to only return the field fromUserId for each object in the array.
Question in comment ("what if I only want to get the ids from friend requests where "accepted" is false?"):
_.pluck(
_.filter(Meteor.user().profile.friendRequests, function (req) {
return !req.accepted;
}),
'fromUserid'
);
Underscore filter docs

Categories

Resources