简体   繁体   中英

Mongodb, get full object from a reference

Does exist anything permitting us to access a full object from a reference with Mongodb ?

For example, I have a User and a Type collection. A user has a Type, stored with a reference to the Type object.

Is it possible to access the full User object with the Type, without lazyloading it ?

Thanks for all

Yes; if you're happy making use of mongoose, then you can use its populate() function:

Populated paths are no longer set to their original _id , their value is replaced with the mongoose document returned from the database by performing a separate query before returning the results.

http://mongoosejs.com/docs/populate.html

So for your User , when performing a query to derive said user, something like this would set up the Type instance:

User.findOne({ username: 'Fred Bloggs' }).populate('type')
  .exec(function (err, user) {
    ...

MongoDB does not do joins. It's not possible to get the information to embed the full Type object in the User document without more than one operation (I guess you have to "lazyload" it, in your terminology). The Mongoose populate() function just handles doing the extra queries and replacing the id with the document for you - it does multiple queries just like any other client doing the same operation would have to. You should think carefully about what types of queries you are doing to determine if it might be a good idea to denormalize the Type object into User documents.

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