I have a mongo document that looks like this :
{
"_id" : "cfqjJW8WZprDSJEop",
"rName" : "z1",
"pName" : "P-4",
"ipAddress" : "21.1.1.12",
"misc" : {
"createdBy" : "admin",
"updatedBy" : "admin",
"creationTime" : ISODate("2016-09-15T09:43:10.953Z"),
"updatedTime" : ISODate("2016-09-15T09:43:10.953Z")
}
}
I have written code on my meteor helper such that during each update, only the updatedBy
and updatedTime
should be pushed on to the mongo document.
The misc object is something that is being added just before the insert / update.
I run into trouble when I try to update the record by using:
doc // contains the update document being generated.
misc = {};
misc.updatedBy = //some name
misc.updatedTime = new Date();
doc.misc = misc,
r.update(id,doc); // calling meteor update
However, when the update happens, what is happening is that the query is completely replacing the misc object within the record (that contains createdBy and creationTime) with what I've passed. I end up losing the creationTime and createdBy fields.
How do I go about updating the object partially?
Since my doc object initially does not contain the misc object, I've also tried injecting in something like :
doc.$set.misc.updatedBy
But it errors out stating that updatedBy does not exist. What's the right way to update a partial object within a document?
Instead of doc.$set.misc.updatedBy
Try this:
doc = {
"$set": {
"misc.updatedBy": "some data"
}
};
Here we are using the MongoDB Dot Notation
to access properties of embedded documents.
Example:
var doc = {
"$set": {
"misc.updatedBy": "some data",
"misc.updatedTime": new Date(),
}
};
r.update(id, doc);