mongojs - How to dynamically $set a subdocument field in mongodb? -
This question is already an answer here
- 2 replies
I have a situation In where I need to dynamically update the value of a field in a sub-document. Area or may not exist already if it is not in existence, then I want to make Mongo to make it.
Here is an example document that will be found in my teams
collection, which is used to store members of any team:
< Code> {_ id: ObjectId ('JKS78678923SDFD678'), name: "Bob Lawblaw", status: "administrator", option: {one: "one", two: "two options
and using the query here (I am using my own Mongo client) code> Sub-document:
var projectID = 'JKS78678923SDFD678'; Var key = 'three'; Va Update: {$ set: {option [key]: value}}, upsert: true, multi: false, r value = 'three'; Teams.findAndModify ({query}: {projectID: mongojs.ObjectId (projectID)}, New: True}, function (error, result, last error object) {console.log (result);});
But I can not get it up to 'upset' value .
I also received a similar question, but that method also did not work:
P> Essentially, you need to create a 'placeholder' object of the subdocument you are trying to update before so like running the query: < / P>
on projectID = 'JKS78678923SDFD678'; Var key = 'three'; Var value = 'three'; Var Placeholder = {}; Placeholder ['Options.' + Key] = value; Teams.findAndModify ({query: {projectID: mongojs.ObjectId (projectID)}, update: {$ set: placeholder}, upsert: true multi: false new: true}, function (error, result, lastErrorObject) {console .log (result);});
It updates any already existing fields, and adds a field / value if it does not already exist.
Comments
Post a Comment