mongodb 2.1.4 (Node driver)
I am currently trying to create a new ObjectID for every message that I insert into an array (the array is a subdocument).
As I understand it, all CRUD operations can be easily performed for each message in the array.
Example:
A collection of "threads" (Note-ObjectId for each message)
{
"_id": ObjectId("1234132413424123"),
messages:[
{
_id :ObjectId("134124412341234"),
"message":"MongoDB is my friend"
},
{
_id :ObjectId("534124412342377"),
"message":"MongoDB is my friend too"
},
...
]
},
{
"_id": ObjectId("22341324134224234"),
messages:[
{
_id :ObjectId("8341244123411235"),
"message":"Something clever"
},
{
_id :ObjectId("134124412342376"),
"message":"blah blah blah"
},
...
]
}
What I'm doing right now:
var query = {};
query["_id"] = new ObjectID(threadID);
var update = {$push: {}};
update.$push["messages"] = newMessage;
var threadsCollection = db.collection('threads');
threadsCollection.findOneAndUpdate(query,update, function (err, result) {
if (err) {
console.log(err);
}
db.close();
});
Problem:
Unlike insert for collections, updating with $ push does not create a new ObjectId for each message added to the array.
Question:
Is there a standard way to create an ObjectID during $ push into a child array? Or do we just manually create an ObjectID and add it to the child in advance?