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 figur
Not a mongodb
expert but, if I understand you correctly, you wish the _id field of the subdocument to be inserted automatically.
I created threads
db and then inserted the first message
in the messages
collection using the following command:
db.messages.insert({messages:[{_id:ObjectId(), message:"Message 1."}]});
Notice the _id:ObjectId()
field. The result is as follow:
Now that I have an ObjectId(56...)
, I can update that particular record and insert more messages to it. And the command is as follow:
db.messages.update({"_id":ObjectId("56...")},
{$push:{messages:{_id:ObjectId(), message:"I am message 2."}}});
And the above would insert the new message in the collection. See below screenshots:
and finally after a few updates the collection looks as follow:
All the _id fields in the messages
array are automatically generated.
It might not be a good idea to use _id
fields for various reasons. Please Google for more details on whether to use _id as key for subdocuments or not.
I used MongoDB shell version 3.0.6 for the commands.
EDIT 28-01-2016 16:09
Since the above solution was based on MongoDB shell, I decided to do another test using Node.js driver for MongoDB. First of all, I declare ObjectID variable as follow
var ObjectID = require('mongodb').ObjectID;
I will use the ObjectID with document id of the thread to which the message should be inserted as follow in my update
and findOneAndUpdate
function calls
app.get('/insertNewMessage', function(req, res) {
db.collection("messages").findOneAndUpdate({
_id: new ObjectID('56aa3554e90911b64c36a424')
}, {
$push: {
messages: {
_id: new ObjectID(),
message: "From NodeJS with <3 using findOneAndUpdate.Bye."
}
}
}, function(err, result) {
if (err)
res.json(err);
else
res.json(result);
});
});
Tested both and works just fine. See the screenshot below:
Sorry for the breech of protocol but I do no have enough rep to comment on the main thread.
I have been looking at how to generate a JSON
insert using ObjectID()
and in my travels have found that this solution is not very good for indexing. The proposed solution has _id values that are strings rather than real object IDs - i.e.
"56a970405ba22d16a8d9c30e" is different from ObjectId("56a970405ba22d16a8d9c30e")
and indexing will be slower using the string. The ObjectId
is actually represented internally as 16 bytes
.