Node.js - 与 Mongoose 创建关系
我有 2 个架构,Custphone
和 Subdomain
。 Custphone
belongs_to
Subdomain
和 Subdomain
has_many
Custphones
。
问题在于使用 Mongoose 创建关系。我的目标是: custphone.subdomain 并获取 Custphone 所属的子域。
我的架构中有这样的内容:
SubdomainSchema = new Schema
name : String
CustphoneSchema = new Schema
phone : String
subdomain : [SubdomainSchema]
当我打印 Custphone 结果时,我得到以下信息:
{ _id: 4e9bc59b01c642bf4a00002d,
subdomain: [] }
当 Custphone
结果在 MongoDB 中具有 {"$oid": "4e9b532b01c642bf4a000003"}
时。
我想要执行 custphone.subdomain
并获取 custphone 的子域对象。
I have 2 Schemas, Custphone
and Subdomain
. Custphone
belongs_to
a Subdomain
and Subdomain
has_many
Custphones
.
The problem is in creating the relationship using Mongoose. My goal is to do: custphone.subdomain and get the Subdomain that the Custphone belongs to.
I have this in my schemas:
SubdomainSchema = new Schema
name : String
CustphoneSchema = new Schema
phone : String
subdomain : [SubdomainSchema]
When I print the Custphone result I get this:
{ _id: 4e9bc59b01c642bf4a00002d,
subdomain: [] }
When the Custphone
result has {"$oid": "4e9b532b01c642bf4a000003"}
in MongoDB.
I want to do custphone.subdomain
and get the subdomain object of the custphone.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来您想尝试 Mongoose 中的新 populate 功能。
使用上面的示例:
subdomain
字段将使用“_id”进行更新,例如:要实际从
subdomain
字段获取数据,您必须使用稍微复杂一点的查询语法:It sounds like you're looking to try the new populate functionality in Mongoose.
Using your example above:
The
subdomain
field will be is updated with an '_id' such as:To actually get data from the
subdomain
field you're going to have to use the slightly more complex query syntax:我遇到了类似的问题,不得不使用 mongoose 的 Model.findByIdAndUpdate()
文档: http:// mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate
这篇文章也帮助了我:http://blog.ocliw.com/2012/11/25/mongoose-add-to-an-existing-array/comment-page-1/#comment-17812
I had a similar problem and had to use mongoose's Model.findByIdAndUpdate()
docs: http://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate
this post helped me also: http://blog.ocliw.com/2012/11/25/mongoose-add-to-an-existing-array/comment-page-1/#comment-17812