Add new field to a specific object in mongoDB - node.js

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

Related

Update String inside object inside array mongodb

I have a document that looks something like this
{
"_id":{
"$oid":"id"
},
"side1":[
{
"username":"test1",
"id":"id1",
},
{
"username":"test2",
"id":"id2",
},
{
"username":"test3",
"id":"id3",
}
],
"side2":[
{
"username":"test4",
"id":"id4",
},
{
"username":"test5",
"id":"id5",
},
{
"username":"test6",
"id":"id6",
}
],
}
I want to be able to search and update one of the sides, for example, if I searched with username for side1 and that username would be there then I would be able to $set other fields for the object with this username. Something like: Search side1 username test1: $set result.id: "43242342" this would set the id of the object with the username of test1 to 43242342. I am not sure on how I would go about doing this, I have tried using $elemMatch but that didn't bring any results.
Test.findOne({ id: id },
{ side1: { $elemMatch: {username: username} } }, function (err, result) {
if (err) {
console.log(err);
} else {
console.log(result)
}
});
I'm not exactly sure how you want to update the document, but perhaps this is what you are looking for?
db.collection.update({
"_id": ObjectId("000000000000000000000001"),
"side1.username": "test1"
},
{
"$set": {
"side1.$.id": "43242342"
}
})
Try it on mongoplayground.net.
Example updated document:
[
{
"_id": ObjectId("000000000000000000000001"),
"side1": [
{
"id": "43242342",
"username": "test1"
},
{
"id": "id2",
"username": "test2"
},
{
"id": "id3",
"username": "test3"
}
],
"side2": [
{
"id": "id4",
"username": "test4"
},
{
"id": "id5",
"username": "test5"
},
{
"id": "id6",
"username": "test6"
}
]
}
]
Could you do something like this?
function addProperty(id, side, username, property, value) {
const query = {
_id: {
$oid: id,
},
};
const update = {
$push: {
[side]: {
username: username,
[property]: value,
},
},
};
const options = {
upsert: true,
};
db.collection("Test").updateOne(query, update, options);
}

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

Replace array of objects with another in Mongo DB

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

How can i get populate my elements name from an array in mongoose with objectid

I'm trying to show the "name" from the "books" collection , what i'm trying to do is get "bookId" with req.paramsbookId and show it in the "history" array instead of bookId itself, thanks for any help
Method: localhost:3000/users/5f0da88156a370091499406f/borrow/5f0cd134fa4ada27787a5d85
exports.borrowBook=asyncHandler(async(req,res,next)=>{
if (req.params.bookId && req.params.id) {
bookId=req.params._id;
userId=req.params.id;
console.log("userid:"+userId);
const bookName=req.params.bookId;
User.findByIdAndUpdate( userId,{ "$push": { history: {"name":bookName} } },{new:true}).exec();
}
res.status(200).json({success:true,msg:'borrow book'});
})
Here is my books collections
{
"_id": {
"$oid": "5f0cd134fa4ada27787a5d85"
},
"name": "test",
"createdAt": {
"$date": "2020-07-13T21:25:08.261Z"
},
"slug": "test",
"__v": 0
}
This is my users collection
{
"name": "Esin Öner",
"history": [{
"name": ["5f0cd134fa4ada27787a5d85"],
"_id": {
"$oid": "5f0daa930643d71380071627"
}
}, {
"name": ["5f0cd134fa4ada27787a5d85"],
"_id": {
"$oid": "5f0dbca1c0402b1aa472b218"
}
}],
"__v": 0
}
For inserting the book name instead of book id in the history array of users document, you would require to first find the book on the basis of the bookId.
And then use the findOneAndUpdate method to update the history array of the user's document.
Also, there is an issue with your implementation of findOneAndUpdate method. The first argument of findOneAndUpdate method is an object instead of a parameter (reference).
You need to make the following changes to get the desired outcome:
exports.borrowBook=asyncHandler(async(req,res,next)=>{
try {
if (req.params.bookId && req.params.id) {
bookId=req.params._id;
userId=req.params.id;
console.log("userid:"+userId);
const bookName=req.params.bookId;
const bookRecord = await Books.find({"_id": bookId});
await User.findByIdAndUpdate( {"_id": userId},{ "$push": { history: {"name":bookRecord.name} } },{new:true}).exec();
}
} catch(e) {
console.log(e);
res.status(400).send(e);
}
res.status(200).json({success:true,msg:'borrow book'});
})

moongose nested subdocument update and delete

"_id": {
"$oid": "577cc50d10b5a6c42b26f414"
},
"firstName": "new",
"lastName": "new",
"__v": 0,
"A": [
{
"AfirstName": "AfirstName",
"AlastName": "AlastName",
"_id": {
"$oid": "577dbef2f2c9f5901f402efe"
},
"AB": [
{
"AB1firstName": "AB1firstName",
"AB1lastName": "AB1lastName",
"_id": {
"$oid": "577dd3b1495663ec2a6ca456"
}
},
{
"AB2firstName": "AB2firstName",
"AB2lastName": "AB2lastName",
"_id": {
"$oid": "577dd3bc495663ec2a6ca45a"
}
}
]
}
]
Example.update({ _id: , A._id: , A.AB._id: } ,
{"$set": {"A.$.AB": data}},
function(err,model){ console.log(model); if (err) throw err; })
This will just update the first data of AB i want to update data of AB sub-doc by _id and also want to remove the particular nested sub-doc with _id
Example.findById(_id,function(err,doc){
var result = doc.A.id(AId).AB.id(AB.ABId);
result.AB1firstName="first Name";
result.AB1lastName= "Last Name";
doc.save();
});
This will update
Each document has an _id. DocumentArrays have a special id method for looking up a document by its _id.
Example.findOne({ _id: id, A._id: Aid, A.AB._id: ABid},
function(err,model){
if (err) throw err;
var ABDoc model.A.id(Aid).AB.id(ABid);
ABDoc.AB2firstName="new value";
ABDoc.AB2lastName="new value";
model.save();
})

Resources