Unable to push data into current object inside mongo database - javascript

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.

Related

Mongoose update inner field

I have this kind of documents in my mongoDB :
{
id: my_id
inner_foo : [
{
inner_id : id_A
inner_field : field_A
},
{
inner_id : id_B
inner_field : field_B
}
]
}
When receiving a request, i got two ids, the id one (here my_id), and the inner_id one (here for example id_A).
How can I, using JS and mongoose, update an inner field ? such as the inner_field field of one of the array contained objet using its inner_id
I think I cannot use findByIdAndUpdate since I can't make a direct reference to the correct inner_foo entry using that method, so how should I do it ?
Many thanks !
Kev.
Demo - https://mongoplayground.net/p/2pW4UrcVFYr
Read - https://docs.mongodb.com/manual/reference/operator/update/positional/
db.collection.update(
{ id: "my_id", "inner_foo.inner_id": "id_A" }, // find the matching document
{ $set: { "inner_foo.$.inner_field": "id_A_Update" }} // set the value on the matched array index
)

How do I update the messageRead attribute in my MongoDb object?

I have the following object stored in MongoDb. I am sending a messageRead attribute inside my messages array.
I have tried:
collection.updateOne({ '_id': ObjectId(employeeID) },
{
"$set": {
"userObject.messages.message.message_uuid" : { employeeMessageUpdateUUID, "messageRead" : employeeMessageRead }
}
but it does not work. I find the object i'm looking for through the _id, and then try to find the message using the message_uuid however the messageRead attribute is not updating. I am clearly using the wrong Mongo query.. What should my $set look like?
You can use $ operator to do that:
collection.updateOne(
{
'_id': ObjectId(employeeID),
'userObject.messages.message.message_uuid': employeeMessageUpdateUUID
},
{
$set: { 'userObject.messages.$.message.messageRead': employeeMessageRead }
}
)...

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.

mongoDB - $push _id to specific users

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

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