mongodb 2.1.4(The Node Driver)
I'm currently trying to create a new ObjectID for each message I insert into an array(the array being a subdocument).
I figure this way - All CRUD operations can easily be performed on each message in the array.
For Example:
The "threads" collection(Note- An ObjectId for each message)
{
"_id": ObjectId("1234132413424123"), //A thread id
messages:[
{
_id :ObjectId("134124412341234"),// A message id
"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 currently doing right now:
var query = {};
query["_id"] = new ObjectID(threadID);
var update = {$push: {}}; //I write the update object externally just for aesthetics
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, an update with $push does not create a new ObjectId for each message added to the array.
Question:
Is there a standard way of creating an ObjectID during a $push into the child array? Or should we just manually create an ObjectID and add it to the child beforehand?