updating nested document with mongoDb + nodeJs - node.js

I have a structure like this:
{
"_id" : ObjectId("501abaa341021dc3a1d0c70c"),
"name" : "prova",
"idDj" : "1",
"list" : [
{
"id" : 1,
"votes" : 2
},
{
"id" : 2,
"votes" : 4
}
]
}
And I'm trying to increase votes with this query:
session_collection.update(
{'_id':session_collection.db.bson_serializer.ObjectID.createFromHexString(idSession),'list.id':idSong},
{$inc:{'list.$.votes':1}},
{safe: true} ,
callback);
But it doesn't work, there are no problems it just doesn't update anything.
I think it's because the ['] (simple quotation mark) on the 'list.id' and 'list.$.votes' because the same query inside the terminal works perfectly.
Thanks!

I suspect your matching is not working as you expect. The callback will return
function(err, numberofItemsUpdated, wholeUpdateObject)
numberofItemsUpdated should equal 1 if your matching worked. you'll need to check if idSession and idSong are what you think they are.

Related

Mongoose update object in an embedded array

I want to update a comment in a post. I first retrieve the post document which looks like this.
{
"_id" : ObjectId("5aac169c229f0136296407d4"),
"title" : "First Node.js App",
"body" : "testing 123",
"status" : "public",
"user" : "John Doe",
"date" : ISODate("2017-12-21T18:30:09.779Z"),
"comments" : [
{
"commentBody" : "This is awesome! ",
"commentUser" : ObjectId("5a3bfd5a9e65351f9c18ba18"),
"_id" : ObjectId("5a3c02379e65351f9c18ba1a"),
"commentDate" : ISODate("2017-12-21T18:49:27.620Z")
},
{
"commentBody" : "This is second comment.",
"commentUser" : ObjectId("5a3bfd5a9e65351f9c18gt19"),
"_id" : ObjectId("5a3c02379e65351f9c18ba1b"),
"commentDate" : ISODate("2017-12-21T18:49:27.620Z")
}
],
"allowComments" : true
}
Let say I want to update comment with "_id" ObjectId("5a3c02379e65351f9c18ba1a").
I've tried the following without luck.
const post = await Post.findById(req.body.postID);
await post.update({'comments._id' : req.body.commentID},{$set : {
'comments.$.commentBody': req.body.comment
}
});
This gave me the following error:
MongoError: cannot use the part (comments of comments._id) to traverse the element
Any suggestion would be greatly appreciated. Thanks in advance!
You can try something like this::
Post.findOneAndUpdate(
{ "_id": req.body.postID, "comments._id": req.body.commentID },
{
"$set": {
'comments.$.commentBody': req.body.comment
}
},
function(err,doc) {
}
);
I'm not sure about how to implement this in node.js but here is the Mongo query:
db.sample.aggregate([
{$match:{"comments.commentUser":ObjectId("5a3bfd5a9e65351f9c18ba19")}},
{$redact:{
$cond:{
if:{$or:[{$eq:["$commentUser",ObjectId("5a3bfd5a9e65351f9c18ba19")]},
{$not:"$commentUser"}]},
then:"$$DESCEND",
else:"$$PRUNE"
}
}},
{$addFields:{comments:{$map:{
input:"$comments",
as:"comment",
in:{"commentBody":"test comment", "commentUser" : "$$comment.commentUser", "_id" :"$$comment._id", "commentDate" :"$$comment.commentDate"}
}}
}},
{$out:"sample"}
])
Restricted the document such that only particular user id comments are displayed. After that, added comments with updated comment. Finally replacing the original content within aggregation without update query(note that collection will get replaced if you run the query). I didnt test this extensively, but working for small data set in my local. However, you might need to add some tweaks to this query and then check how u can add same query to node.js

Delete comments inside array using index value using mongoose

I have to delete the second comment using index value.. Following is my document structure
{
"_id" : ObjectId("000000000fea5f24282e715b"),
"file_name" : "resume_of_ganga_.docx",
"created_date" : ISODate("2017-11-28T10:29:10.373Z"),
"updated_date" : ISODate("2017-11-28T12:39:32.148Z"),
"comments" : [
{
"created_date" : ISODate("2017-11-28T13:23:51.472Z"),
"status" : "N",
"comment_text" : "Yes...",
"username" : "name"
},
{
"created_date" : ISODate("2017-11-28T13:24:15.938Z"),
"status" : "N",
"comment_text" : "asdsd",
"username" : "name"
}
]
}
I have using this following mongoose query..But my comments are not get deleting
mongo.filemanager.findOneAndUpdate({ "_id": req.body.id},{$pull : {"'comments.' +req.body.c_index" : 1 }},function(err,response){
console.log("Deleted")
});
For example am getting index value as 2.. It should delete the second comment...
Thanks in Advance
I tried looking up to see if MongoDB has any such functionality but seems like they don't from what I found.
A workaround could be something like this. Not sure if this can be considered an atomic operation.
const removeCommentAtIndex = (index) => {
mongo.filemanager.findById(req.body.id, (err, file) => {
file.comments.splice(index, 1);
file.save();
})
}
I executed the accepted answer for In mongoDb, how do you remove an array element by its index in my test database and IT WORKS
mongo.filemanager.findOneAndUpdate({}, {"$unset" : {"comments.1" : 1 }})
mongo.filemanager.findOneAndUpdate({}, {"$pull" : {"comments" : null}})
Note that your req.body.c_index needs to be 1 to remove 2nd comment.

update array in mongoose which matches the condition

my schema looks like
{
qty:{
property1:{
//something
}
property2:[{
size:40,
color:"black",
enabled:"true"
}]
}
}
property 2 is array what i want to do is update those array object whose enabled is true in single query
I tried writing the following query
db.col.update({
"qty.property2.enabled" = "true"
}, {
"qty.property2.color" = "green"
}, callback)
but it is not working
error:
[main] Error: can't have . in field names [qty.pro.size]
db.col.update({"qty.property2.enabled":"true"},{$set: {'qty.property2.$.color': 'green'}}, {multi: true})
this is the way to update element inside array.
equal sign '=' cannot be used inside object
updating array is done using $
Alternative solution for multiple conditions:
db.foo.update({
_id:"i1",
replies: { $elemMatch:{
_id: "s2",
update_password: "abc"
}}
},
{
"$set" : {"replies.$.text" : "blah"}
}
);
Why
So I was looking for similar solution as this question, but in my case I needed array element to match multiple conditions and using currently provided answers resulted in changes to wrong fields.
If you need to match multiple fields, for example let say we have element like this:
{
"_id" : ObjectId("i1"),
"replies": [
{
"_id" : ObjectId("s1"),
"update_password": "abc",
"text": "some stuff"
},
{
"_id" : ObjectId("s2"),
"update_password": "abc",
"text": "some stuff"
}
]
}
Trying to do update by
db.foo.update({
_id:"i1",
"replies._id":"s2",
"replies.update_password": "abc"
},
{
"$set" : {"replies.$.text" : "blah"}
}
);
Would result in updating to field that only matches one condition, for example it would update s1 because it matches update_password condition, which is clearly wrong. I might have did something wrong, but $elemMatch solution solved any problems like that.
Suppose your documet looks like this.
{
"_id" : ObjectId("4f9808648859c65d"),
"array" : [
{"text" : "foo", "value" : 11},
{"text" : "foo", "value" : 22},
{"text" : "foobar", "value" : 33}
]
}
then your query will be
db.foo.update({"array.value" : 22}, {"$set" : {"array.$.text" : "blah"}})
where first curly brackets represents query criteria and second one sets the new value.

how to prevent auto deletion collection records from Mongodb

Hello all I got stuck somewhere, I am working on mongodb with node.js where my collection data deleted automatically after 1 year on certain date and I want to stop that permanently how can I do that ? I have checked the available material on google but didn't got much success please help me friends ...
I have checked the index in one of my collection and it is showing data like this . Can you please tell me its is having TTL index or not
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "firstfive.teachers"
},
{
"v" : 1,
"key" : {
"_fts" : "text",
"_ftsx" : 1
},
"name" : "firstname_lastname_text",
"weights" : {
"firstName" : 1,
"lastName" : 1
},
"default_language" : "english",
"language_override" : "language",
"ns" : "firstfive.teachers",
"textIndexVersion" : 2
}
]
most likely you have TTL (time to limit) index defined on collection you're working with (https://docs.mongodb.com/v3.2/core/index-ttl/)
yu can check it by running db.your_collection.getIndexes() (it will be one with expireAfterSeconds) in mongo shell.
as any other index it can be removed - but do it carefully, apparently someone did it deliberately

Querying a property that is in a deeply nested array

So I have this document within the course collection
{
"_id" : ObjectId("53580ff62e868947708073a9"),
"startDate" : ISODate("2014-04-23T19:08:32.401Z"),
"scoreId" : ObjectId("531f28fd495c533e5eaeb00b"),
"rewardId" : null,
"type" : "certificationCourse",
"description" : "This is a description",
"name" : "testingAutoSteps1",
"authorId" : ObjectId("532a121e518cf5402d5dc276"),
"steps" : [
{
"name" : "This is a step",
"description" : "This is a description",
"action" : "submitCategory",
"value" : "532368bc2ab8b9182716f339",
"statusId" : ObjectId("5357e26be86f746b68482c8a"),
"_id" : ObjectId("53580ff62e868947708073ac"),
"required" : true,
"quantity" : 1,
"userId" : [
ObjectId("53554b56e3a1e1dc17db903f")
]
},...
And I want to do is create a query that returns all courses that have a specific userId in the userId array that is in the steps array for a specific userId. I've tried using $elemMatch like so
Course.find({
"steps": {
"$elemMatch": {
"userId": {
"$elemMatch": "53554b56e3a1e1dc17db903f"
}
}
}
},
But It seems to be returning a empty document.
I think this will work for you, you have the syntax off a bit plus you need to use ObjectId():
db.Course.find({ steps : { $elemMatch: { userId:ObjectId("53554b56e3a1e1dc17db903f")} } })
The $elemMatch usage is not necessary unless you actually have compound sub-documents in that nested array element. And also is not necessary unless the value being referenced could possibly duplicate in another compound document.
Since this is an ObjectId we are talking about, then it's going to be unique, at least within this array. So just use the "dot-notation" form:
Course.find({
"steps.userId": ObjectId("53554b56e3a1e1dc17db903f")
},
Go back and look at the $elemMatch documentation. In this case, the direct "dot-notation" form is all you need

Resources