admin管理员组

文章数量:1323208

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": "[email protected]"
    , "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...

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": "[email protected]"
    , "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...

Share Improve this question edited Jul 22, 2012 at 16:13 Asya Kamsky 42.4k5 gold badges112 silver badges133 bronze badges asked Jul 22, 2012 at 15:17 bodokaiserbodokaiser 15.8k27 gold badges100 silver badges143 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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" : "[email protected]",
    "username" : "kyogron"
}

In mongo shell run the following update:

db.collection.update({"_id" : ObjectId("500abe6a25dff13c7c000001")},
                     {$push:{"contacts": ObjectId("500abe6a2543213c7c000002")}})

Use appropriate ObjectId values for your specific case.

本文标签: javascriptHow do I manually add a reference in MongoDBStack Overflow