简体   繁体   中英

MongoDB - Update field with reference of another document

I would like if is possible to update a field of all documents in a collection with a reference to another document. I have tried to do this with the code below:

var project = db.Project.find({slug:"engine"});

db.Activity.update({}, {$set:{'project':DBRef("Project", project._id, "mydb")}});

When I look at the Activity documents, in the "project" field, the result is:

{
  _id: ObjectId("..."),
  "project": DBRef("Project", undefined, "mydb")
}

Is there a way to do this correctly?

Thanks in advance.

Seems to me you're having a promise callback problem. You can solve it in two ways:

Option one: Put the function depending of your data return inside a callback of the first function, for example:

db.Project.find({slug:"engine"}, function(error, data) {
    db.activity.update(...data.Id...);
});

Option two: Wait for the return of the find to be completed:

var project = db.Project.find({slug:"engine"});

project.then(function(error,data) {
       db.activity.update(...project.Id...);
});

Both should work. The problem is that when you make the first call, it returns a promise, not the value itself. If you are making confusion on this topic, you can take a look at:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Hope my answer helped you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM