Hello how to update object field inside array of objects in MongoDB collection?
Structure of document is like this:
{
_id: ObjectId("60ebee6c2d610c17e4df2445")
languages: [ {code:"eng", word:"house", diff:23}, {code:"deu", word:"Hause", diff:6} ]
}
I tried with this query:
for (const sent of temparray) {
try {
Content.update({_id : sent.id , 'languages.code':'eng'} , { $set:
{
'languages.$.word' : sent.min.word
}
})
} catch (err) {
console.log('error updating document:', err)
}
}
I want to update field word in each eng sentence.
I'm using node js and express server.
But nothing happened any idea whats wrong?
Related
I'm building REST APIs in node.js using express.js library.
For the embedded data stored in mongodb as json object, I'm trying to get specific data by filtering, thereby using the aggregate match to achieve so.
For the users collection, I've the data as below
[
{
unique_key:"1",
user_form:
{
user_details:
{
first_name:"Tely",
last_name:"Zed"
}
}
},
{
unique_key:"2",
user_form:
{
user_details:
{
first_name:"Rock",
last_name:"Monty"
}
}
}
]
I want to get data of user by searching name. So I'm using aggregate method and then using match operator to achieve it.
User is the name of the model.
For filtering I'm using below aggregate method on User model.
User.aggregate([
{
$match: {
user_form:
{
user_details:
{
first_name: req.body.user_form.user_details.first_name
}
}
}
}
])
.exec(function(err,filteredUsers){
if(filteredUsers) {
console.log(filteredUsers);
res.json({
"msg": "Successfully gets the filtered users",
"data": filteredUsers,
"success": true
});
} if(err){
res.json({
"msg":"Error occured while filtering users",
"error": err ,
"success":false
});
}
})
//Now when I'm posting request from postman with searching with first_name as Rock in postman //body as shown below.
{
user_form:
{
user_details:
{
first_name:"Rock"
}
}
}
//So upon hitting send, I'm getting below response in postman, so I'm not able to get filtered //data instead getting an empty array.
{
"msg": "Successfully gets the filtered users",
"data": [],
"success": true
}
So please tell what should I do to filter data .
Used dot notation to query for subdocument.
db.users.aggregate([
{$match:{"user_form.user_details.first_name":"Rock"}}]).pretty()
Output:
{
"_id" : ObjectId("63c01a42232f174edd983fbf"),
"unique_key" : "2",
"user_form" : {
"user_details" : {
"first_name" : "Rock",
"last_name" : "Monty"
}
}
}
The mistake I did was I kept a space in "first_name" like "first_name " while inserting the document, so that's why I wasn't able to get filtered data by dot notation method also, so later I did found by same query.
I'm trying to update an object that is inside a multi nested array in Mongodb. I know that I cannot use the positional $ operator for multi nested arrays. So I'm trying to use arrayFilters instead.
Here is my query structure:
var objTest = {
name: 'blah',
color: 'blablah'
}
SomeModel.updateOne(
{
an_id: anId,
"an_array.another_array.and_another_array.some_id": id,
},
{
$set: {
"an_array.$[element].another_array.$[another_element].and_another_array": objTest,
},
},
{
arrayFilters: [
{ "element.name": 'test' },
{ "another_element.id": 'test2' },
],
}
)
.then((result) => {
console.log("result ", result);
resolve(result);
})
.catch((err) => {
console.log("err is ", err);
reject(err);
});
So as per the example, I'm trying to update the object that matches some_id in the and_another_array array. When I try this, I'm receiving the error The top-level field name must be an alphanumeric string beginning with a lowercase letter, found 'another_element'
I don't understand what I'm doing wrong here.
I was able to figure out what the issue was. For some reason, mongodb didn't like the in another_element. renaming it to anotherelement worked.
Let's take an exemple :
listCollection = {
id_list:"111",
child_list:[{
id_list:"222",
child_list:[{
id_list:"333",
child_list:[{
// and it can be more
}]
}]
}]
}
As you see, it is always the same object inside the same object. The initial object is :
var list = {
id_list: "string",
child_list:[]
};
Using mongoDB, I would like to Find, Update or Push list anywhere I want inside the collection, only by knowing the id_list.
This is the most far I was :
db.collection("listCollection").findOneAndUpdate({
"child_list.id_list": "listId"
}, {
"$push": {
"child_list.$.child_list": newList
}
}, function(err, success) {
if (err) {
console.log(err);
} else {
console.log(success);
}
})
It works fine for the first level of child, but not more.
I am pretty new to Node JS + mongoDB, can you help me a little bit with this ? Thank you :)
I have found my way through this. Not a really beautiful one, but a working one.
Let's retake my exemple :
listCollection = {
child_list:[{
child_list:[{
child_list:[
]
}]
}]
}
I want to add a new child_list at the end of the hierarchy. At the end, I want my collection to look like that :
listCollection = {
child_list:[{
child_list:[{
child_list:[{
child_list:[
]
}]
}]
}]
}
Yeah, it is kind of a dumb exemple but it is a simple one :)
So here is the object I want to insert :
var theNewChildList= {
child_list:[]
};
Then, I will need a kind of "route" of where I want to put theNewChildList.
Here, I want to push it at listCollection.child_list[0].child_list[0].child_list
So I just use that string :
var myRoute = "child_list.0.child_list.0.child_list";
Then, I prepare your mongoDB query like that :
var query = {};
query[myRoute] = theNewChildList;
and finally, I do the query :
db.collection("myCollectionOfList").findOneAndUpdate(
{}, // or any condition to find listCollection
{"$push": query},
function(err, success) {
if (err) {
console.log(err);
} else {
console.log(success);
}
})
And it works.
Note that you have many ways to prepare the var myRoute dynamically.
I you have other ideas, please share :)
So I am currently working on a project with mongodb and nodejs and I was wondering, how can you update data in mongodb via nodejs? My problem is that I want to keep the old data and add new. For example, here is the data currently in my mongodb
{
"_id" : ObjectId("5a1c0c1c3b147ec2e31cceb3"),
"event_id" : "1",
"event_medium" : "null",
"event_tags" : ["#JustTesting"]
}
So I want to add new data to the event_tags array and still keep the old data.
So for example the end result would be this:
{
"_id" : ObjectId("5a1c0c1c3b147ec2e31cceb3"),
"event_id" : "1",
"event_medium" : "null",
"event_tags" : ["#JustTesting", "#Test", "#Something"]
}
You should use the update function of MongoDB for that. MongoDB knows different update operators, in your case you may use $push or $pushAll (the second is deprecated):
update one after the other with $push
YourCollection.update({ _id: 'xxx' }, { $push: { event_tags: '#Test' } });
YourCollection.update({ _id: 'xxx' }, { $push: { event_tags: '#Something' } });
or both at once with $pushAll (deprecated now)
YourCollection.update({ _id: 'xxx' }, { $pushAll: { event_tags: ['#Test', '#Something'] } });
To interact with MongoDB form your NodeJS app, I would use a library like this one.
Your starting point is the Update function in CRUD (Create,Read, Update, Delete) operations in Mongodb.
Your node program should have among others the update function where you set the _id field you want to update and load the content fields to be update in 'data' for example as below:
myModel.prototype.update = function (_id, data, callback) {
const query = { _id: this.mongo.ObjectId(_id) };
debug(' update:' + JSON.stringify(query));
this.mongo.collection('mycollection').update(query, data, callback);
};
This piece of code should be put in your Model, if you use MVC pattern.
There is a lot to go.
Honestly I recommend a more deep tutorial like parts 3 and 4 of this one for nodejs and Mongoose (mongo db driver):
MDN tutorial for mongo/node/express
I assume you are using mongoose..
eventModel.findOne({event_id:1 },
function(err, eventObj){
if(err){
//handle error
} else {
if(eventObj === null) {
//event doesnot exist
}
var tagList = eventObj.event_tags;
tagList.push('new_tag1');
tagList.push('new_tag2');
eventObj.event_tags = tagList;
eventObj.save(function(err){
if(err){
//handle error
} else {
//success
}
})
I am trying to update collection using mongoose with NodeJS .when I log data to NodeJs console it prints the data but not data is not being pushed in collection.
But when i run the same query on mongodb console then it works
Here's the code
portoflio is array of objects
portfolio_user={
'title' : 'this is the sample link',
'type" : 'link',
'url" : 'www.emumba.com'
}
var user_id=req.user._id;
console.log(user_id);
var portfolio_user=req.body;
console.log(portfolio_user)
User.update({_id:user_id},{
$push:{
"portfolio":portfolio_user
}
},
function(err, user){
if (err) {
console.log(err);
} else {
console.log(user);
res.jsonp(user);
}
});
Note: I have also tried findOneAndUpdate and findById but they still dont work