简体   繁体   English

Mongodb,从参考中获取完整的对象

[英]Mongodb, get full object from a reference

Does exist anything permitting us to access a full object from a reference with Mongodb ? 是否存在任何允许我们使用Mongodb从引用访问完整对象的东西?

For example, I have a User and a Type collection. 例如,我有一个用户和一个类型集合。 A user has a Type, stored with a reference to the Type object. 用户具有一个Type,该Type与对Type对象的引用一起存储。

Is it possible to access the full User object with the Type, without lazyloading it ? 是否可以在不延迟加载的情况下使用Type访问完整的User对象?

Thanks for all 谢谢大家

Yes; 是; if you're happy making use of mongoose, then you can use its populate() function: 如果您乐于使用猫鼬,则可以使用其populate()函数:

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. 填充路径不再设置为其原始_id,通过在返回结果之前执行单独的查询,将其值替换为从数据库返回的猫鼬文档。

http://mongoosejs.com/docs/populate.html 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 ,在执行查询以派生该用户时,类似这样的操作将设置Type实例:

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

MongoDB does not do joins. MongoDB不执行联接。 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). 如果不进行一项以上的操作,就不可能获得将完整Type对象嵌入到User文档中的信息(我想您必须用术语“延迟加载”它)。 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. Mongoose populate()函数只是为您处理多余的查询,并为您替换文档中的id-它会执行多个查询,就像执行相同操作的任何其他客户端一样。 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. 您应该仔细考虑正在执行的查询类型,以确定将Type对象反规范化为User文档是否是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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