猫鼬加盟数据 [英] Mongoose joining data

查看:58
本文介绍了猫鼬加盟数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的MongoDB中有一个对象需要在系统中的任何地方使用,那么它在它自己的集合中.但是,我还不太清楚如何使数据自动显示在所连接的其他对象上.
这是一个示例:

If I have an object in my MongoDB that will need to be used EVERYWHERE in my system, so it is in its own collection. However, I con't quite figure out how to get the data to show up automatically on the other objects it is joined to.
Here is an example:

Schema1 = { name: String }  
Schema2 = { something: String, other_thing: [{schema1_id: String}] }

现在我要说的是var name = mySchema2.name;并获取链接的Schema1对象的名称.
我正在使用Mongoose,Express和Node.js,并且曾尝试使用Mongoose的虚拟",但是当我说res.send(myobject);时,在对象的任何位置都看不到虚拟属性.

Now what I want is to be able to say var name = mySchema2.name; and get the name of the linked Schema1 object.
I am using Mongoose, Express and Node.js and I have tried using a Mongoose 'virtual' for this, but when I say res.send(myobject); I don't see the virtual property anywhere on the object.

做到这一点的最佳方法是什么?

What is the best way to do this?

推荐答案

我知道您发布问题已经很久了,但它可能会对其他人有所帮助.
如果您始终使用此参考,则可能需要考虑使用嵌入式文档.嵌入式文档的好处是可以在查询父文档时获得它们,从而节省了额外的查询,而缺点是父文档可能会变大(甚至非常大),因此应使用它们,但要小心使用. br> 这是一个简单的嵌入式文档的示例.我们将其嵌入(代码有点伪),而不是在后文档中引用需要额外查询的评论":

I know it is far after you post the question but it might help others.
If you use this reference all over you may want to consider using embedded document. The benefits of embedded document is that you get them when you query the parent document thus it save you additional query and the drawbacks is that the parent document may become large (or even very large) thus you should use them but use them carefully.
Here is an example of simple embedded document. Instead of referencing 'comments' in the post document, which require additional query, we will embed it (code is a bit pseudo):

var postSchema = new Schema({
  author : {type : String}, 
  title : {type : String, required : true},
  content : {type : String, required : true},
  comment : {
    owner : {type : String},
    subject : {type: String, required : true},
    content : {type String, required : true}
  }
});

MongoDB使您可以通过点字符来查询注释字段的简便方法.例如,如果我们只想查询主题以汽车"开头的评论,请按照以下步骤操作:

MongoDB allows you a simple and convenience way to query comments' fields by the dot character. For example if we like to query only comments which their subject starts with 'car' we do as follow:

myPostModel.find({ 'comment.subject' : /car*/ }).exec(function(err, result){
    Do some stuff with the result...
});

请注意,为简化示例,帖子中的注释字段不是数组(在此示例中,每个帖子允许一个注释).但是,即使它将是一个数组,mongo也以相同的方式非常优雅地引用了数组的元素.

Note that for simplicity of the example the comment field in the post is not an array (one comment per post is allowed in this example). However even if it will be an array, mongo refer to array's elements very elegantly in the same way.

这篇关于猫鼬加盟数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆