Replace array of objects with another in Mongo DB - node.js

I need to replace members array data with new array of objects mems given below.
{
"name": "Test Group",
"members": [{
'userId': {
$oid: 'fjkfkffy'
},
name: 'Himanshu'
}],
"athletes": [],
"leads": []
}
Here I want to replace members array of object with new array of objects. I basically need to overwrite that members array. I've been trying to do something like this below, but I got an error. Can anyone please help me out?
const mems = [{
"user": {
"$oid": "6093a4a709cc0b000d31ber8",
},
"role": "manager"
},
{
"user": {
"$oid": "60a3aea6ecbf4398f01aa598"
},
"role": "user"
}
];
entities.findOneAndUpdate({
_id: ObjectID(entityID),
"groups._id": ObjectID(groupID)
}, {
$set: {
'groups.$.name': name,
'groups.$.members': mems
}
}, {
'new': true
});

Related

How to filter record from array of object in mongoose

Database
{
"followings": [],
"post": [],
"saved": [],
"tagged": [],
"_id": "637661a7454b5127be5baeb4",
"username": "shiv_yadav",
"password": "12345",
"emailorphone": "99999",
"name": "Shiv Yada",
"Saved": [],
"Tagged": [],
"__v": 0,
"bio": "test newBiofssx",
"profileimg": "http://localhost:4100/images/637661a7454b5127be5baeb4-shiv_yadav-1670158119497-jan-kopriva-pfsNJ0wUT5E-unsplash.jpg",
"email": "test#test.cosmd",
"gender": "Male",
"notification": [
{
"notiticationId": "1672147216504",
"type": "RequestedToFollow",
"requester": {
"_id": "637722bdd78bd1ecef887b44",
"username": "vik_choudhar",
"profileimg": "http://localhost:4100/images/637722bdd78bd1ecef887b44-vik_choudhary-1670321337541-pexels-bess-hamiti-35188.jpg",
"name": "Vikash"
},
"readed": false
},
{
"notiticationId": "1672201273818",
"type": "RequestedToFollow",
"requester": {
"_id": "63772408d78bd1ecef887b47",
"username": "Jay_B",
"profileimg": null,
"name": "Jay"
},
"readed": false
},
{
"notiticationId": "1672201356611",
"type": "RequestedToFollow",
"requester": {
"_id": "6377244ad78bd1ecef887b4a",
"username": "Urvesh_V",
"profileimg": null,
"name": "Urvesh"
},
"readed": false
}
],
}
I am using a mongoose. I have a record of users. I am making the notification feature. I have an array of objects for notification fields. I want to update the notification status (Here the field "readed") for id(1672147216504,1672201273818) from false to true of any particular user. Here id means the time field in the object. I have read the document, but it's not updated when I update the field.
I don't know where I am making a mistake.
Can anyone tell me how I can do that?
I have tried the following code.
const notiticationIds = [1672147216504, 1672201273818]
const data = await user.findOneAndUpdate(
{ _id: userid, 'notifications.notiticationId': notiticationIds }, {
'$set': {
'notifications.$.readed': 'true',
}
})
One option is to use $[<identifier>] in order to choose the specific items to update inside the array. If you want to get back the document after the update (this is not the default), use returnNewDocument: true
const data = await user.findOneAndUpdate(
{_id: userid,
notification : {
$elemMatch: {
notiticationId: {$in: ["1672147216504", "1672201273818"]}
}
}},
{$set: {"notification.$[item].readed": true}},
{
arrayFilters: [{"item.notiticationId": {$in: ["1672147216504", "1672201273818"]}}],
returnNewDocument: true
}
)
See how it works on the playground example

How to use $pull to delete a particular data from a document in mongoDB

I'm pretty new in MongoDB,I want to delete a particular object from an array of objects in a document. I tried a lot and finds a lot of questions in StackOverflow.But none of them worked (maybe it's my fault)
following is a document from a collection that is matched by the user with userId
61f15af01a3c53dfa87e38e6
The Document
{
"_id": "61f15af01a3c53dfa87e38ed",
"user": "61f15af01a3c53dfa87e38e6",
"transactions": [
{
"amount": 50,
"category": "Bills",
"type": "Expense",
"_id": "61f15af01a3c53dfa87e38ee"
},
{
"amount": 100,
"category": "Lottery",
"type": "Income",
"_id": "61f15af01a3c53dfa87e38ef"
},
{
"amount": 200,
"category": "Salary",
"type": "Income",
"_id": "61f15af01a3c53dfa87e38f0"
},
]
}
I want to delete the transaction with an Id of 61f15af01a3c53dfa87e38ef
I tried the below one (I don't know whether it is correct)
const allTransactions = await Transactions.findOne({ user: req.user._id });
const updatedTransactions = await allTransactions.update(
{ },
{ $pull: { transactions: { id: req.params.id } } },
);
Can anyone Spot the mistake and how can I achieve it ?
Thanks in advance :)
You can do it in one database call using below statement:
await Transactions.update(
{ user: "61f15af01a3c53dfa87e38e6" },
{ $pull: { "transactions": { _id: "61f15af01a3c53dfa87e38f0" } } }
)
Mongo Playground
Also make sure types match. If _id is of type ObjectId instead of string you should convert req.params.id to ObjectId first. See below:
await Transactions.update(
{ user: mongoose.Types.ObjectId(req.user._id) },
{ $pull: { "transactions": { _id: mongoose.Types.ObjectId(req.params.id) } } }
)

mongodb lookup in array

when i do a lookup in mongodb i enter an as field and the data is loaded into this field. But if I have an array of objects and one of the fields is a REF field then I always have the problem that the data from the lookup is always loaded into a separate field and I cannot find it with the array. How can I do a lookup that loads the data directly into the array element.
for example
i have a organisation with an array of users and there status and role in the organisation
{
_id: "60cc87da3a530000173f6d33",
"baseData": {
"name": "Organisation 1",
"email": "org#gmail.com",
"image": "",
"description": "desc",
"users": [
{
userID: "60cc87803a530000173f6d2d",
userStatus: "active" ,
userOrgRole: "Admin"
},
{
userID: "60cc87803a530000173f9h4u",
userStatus: "active" ,
userOrgRole: "User"
}
]
}
}
when i made a lookup an define the as field as baseData.users the user array are overwirte with the user data. But how i can add the data to each users array.
for example this is the result i need
{
_id: "60cc87da3a530000173f6d33",
"baseData": {
"name": "Organisation 1",
"email": "org#gmail.com",
"image": "",
"description": "desc",
"users": [
{
userID: "60cc87803a530000173f6d2d",
userStatus: "active" ,
userOrgRole: "Admin"
// userdata data from lookup for each array
},
{
userID: "60cc87803a530000173f9h4u",
userStatus: "active" ,
userOrgRole: "User"
// userdata data from lookup for each array
}
]
}
Try this way, add these stages to aggregation pipeline. It will help to add user details..
{
$unwind: {
path: "$baseData.users",
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: "users", // replace with your collection name
localField: "baseData.users.userID",
foreignField: "_id",
as: "baseData.users",
},
},
{
$group: {
_id: "$_id",
baseData: {
$push: "$baseData",
},
},
},

Add new field to a specific object in mongoDB

I want to add a new field to a an object after i search the specific object,
Database looks like this:
{
"_id": {
"$oid": "608378ef1ae6b1368c6220c6"
},
"username": "paul",
"password": "cacavaca123",
"question": "q1",
"answer": "cutu"
}
{
"_id": {
"$oid": "6084c1b557f2242bcc629440"
},
"username": "mircea",
"password": "123456",
"question": "q1",
"answer": "cutu"
}
And i want to search in db for the object with username: paul and add a new field friends:[alex], I have tried this but its not working:
MongoClient.connect(uri, function(err, db) {
var dbc = db.db("chat");
dbc.collection("accounts").find({username: { $eq: user}}).aggregate( [
{
$addFields: {
frequent:[new_friend]
}
}
])
db.close();
});
Also if you know, can you tell me how to update that array of friends and add a new friend to that array?
You've to use update query to do so
Read - updateOne
Demo - https://mongoplayground.net/p/mrTg0DKtnrW
db.collection.update(
{ "username": "paul" },
{
$set: {
friends: ["alex" ]
}
})
Aggregation demo - https://mongoplayground.net/p/yiJgkrgdeHZ

manage and remove objectId from array - mongoose

i have this schema structure
{
"_id": {
"$oid": "571251dae4b065a8c4d70ce1"
},
"email": "somthing12345#gmail.com",
"events": [
{
"$oid": "57125378e4b065a8c4d70d10"
},
{
"$oid": "571253b8e4b065a8c4d70d1b"
}
],
"valid": true,
}
and my problem is this part
"events": [
{
"$oid": "57125378e4b065a8c4d70d10"
},
{
"$oid": "571253b8e4b065a8c4d70d1b"
}
]
how to remove object in this structure?
can i add fields to each one of thos "events" objects like-
"title" : "some string".
how should i add this?
thanks.
For removing:
events.update({
_id: "571251dae4b065a8c4d70ce1"
}, {
$pull: {
events: {
$oid: "57125378e4b065a8c4d70d10"
}
}
}, {
safe: true
}, function(err, obj) {
// code goes here
});
And what about adding field title: "some string", mondoDB at this moment doesn't allow multiple update for embedded documents, so the only one way to achieve your goal is select document from db, then take this document events array and add title to each object of array. save whole document whith changed events array. Hope you understand everything :)

Resources