2

The structure of my document in collection is this.

{ 
"_id" : ObjectId("54e74de2950fd3a4e5f0a37a"),
"userName": "Any_user",
"ratings": {
   "rating1" : [ ],
   "big_rating" : [ ] 
  }
}

In MongoDB client (mongo.exe) the adding i need looks like this

db.userContent.update({userName: "NXTaar"}, {$set: {"ratings.variable_name": []}})

I need the function for the MongoDB node.js driver And yes, i know the "property name as string" thing there i can pass the variable to the property name. Here is what i tried to make:

var rating = {};
var title = 'some_string';
ratings[title] = [];

usercontent.update({userName: "some_user"}, {$set: ratings}, function (err, doc) {...})

this line adds a new object to the document with a name of property

usercontent.update({userName: "some_user"}, {$set: {ratings: ratings}}, function (err, doc) {...})

and this one does exactly what i need, but each time it runs, it rewrites current property with a new one(yes, i know, it because of $set parameter which changes selected object with the thing that you've passed to it)

I need a function which adds a property to object with a name given through variable

1

1 Answer 1

6

Like so:

var t = "property_name"
var field_name = "ratings." + t
var update = { "$set" : { } }
update["$set"][field_qname] = []
db.usercontent.update({ "userName" : "some_user" }, update)

Construct the proper dot notation field name and then the proper $set update expression, then pass that to the update function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.