How do I manually add a reference in MongoDB?
javascript, mongodb, reference
Solution
This worked for me from the MongoDB shell, I'm using `$addToSet` instead of `$push` because I assume you want to avoid dupes:
var o = new ObjectId();
db.foo.update({}, {$addToSet : {"contacts" : o}});
var o = new ObjectId();
db.foo.update({}, {$addToSet : {"contacts" : o}});
That gave me a document that looks like this (my foo collection only contained your sample, so I didn't have to have a specific matching criteria):
{
"_id" : ObjectId("500c2118c78bb07bfbb69eb3"),
"contacts" : [
ObjectId("500c20efc78bb07bfbb69eb2"),
ObjectId("500c227ac78bb07bfbb69eb6")
],
"email" : "kyogron@example.de",
"username" : "kyogron"
}
Problem
I am accessing MongoDB documents with a node.js web-front-end while in developement. I got now following document: ``` { "_id": ObjectID("500abe6a25dff13c7c000001") , "username": "kyogron" , "email": "kyogron@example.de" , "contacts": [ObjectID("500abe6a2543213c7c000002")] // this should contain other user's id } ``` I now want to add another user_id to the contacts array manually, before implementing the feature in the front-end. As you see above I alread tried this using the ObjectID keyword but this didn't work...