mongoDB : Creating An ObjectId For Each New Child Added To The Array Field -
mongodb 2.1.4(the node driver)
i'm trying create new objectid each message insert array(the array being subdocument).
i figure way - crud operations can performed on each message in array.
for example:
the "threads" collection(note- objectid each message)
{ "_id": objectid("1234132413424123"), //a thread id messages:[ { _id :objectid("134124412341234"),// message id "message":"mongodb friend" }, { _id :objectid("534124412342377"), "message":"mongodb 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: {}}; //i write update object externally 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" collections, update $push not create new objectid each message added array.
question:
is there standard way of creating objectid during $push child array? or should manually create objectid , add child beforehand?
not mongodb expert but, if understand correctly, wish _id field of subdocument inserted automatically.
i created threads db , inserted first message in messages collection using following command:
db.messages.insert({messages:[{_id:objectid(), message:"message 1."}]}); notice _id:objectid() field. result follow:
now have objectid(56...), can update particular record , insert more messages it. , command follow:
db.messages.update({"_id":objectid("56...")}, {$push:{messages:{_id:objectid(), message:"i message 2."}}}); and above insert new message in collection. see below screenshots:
and after few updates collection looks follow:
all _id fields in messages array automatically generated.
it might not idea use _id fields various reasons. please google more details on whether use _id key subdocuments or not.
i used mongodb shell version 3.0.6 commands.
edit 28-01-2016 16:09
since above solution based on mongodb shell, decided test using node.js driver mongodb. first of all, declare objectid variable follow
var objectid = require('mongodb').objectid; i use objectid document id of thread message should inserted follow in update , 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 <3 using findoneandupdate.bye." } } }, function(err, result) { if (err) res.json(err); else res.json(result); }); }); tested both , works fine. see screenshot below:




Comments
Post a Comment