Node.js - 用Mongoose创建关系 [英] Node.js - Creating Relationships with Mongoose
问题描述
我有2个架构, Custphone
和子域
。 Custphone
belongs_to
a 子域名
和子域名
has_many
客户
。
<问题是使用Mongoose创建关系。我的目标是:custphone.subdomain并获取Custphone所属的子域。
我的模式中有这个:
SubdomainSchema = new Schema
name:String
CustphoneSchema = new Schema
phone:String
subdomain :[SubdomainSchema]
当我打印Custphone结果时,我得到:
{_ id:4e9bc59b01c642bf4a00002d,
subdomain:[]}
当 Custphone
结果 {$ oid:4e9b532b01c642bf4a000003}
在MongoDB中。
我想要 custphone.subdomain
并获取服务器的子域对象。
听起来你想要尝试新的人口功能。
使用上面的示例:
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
SubdomainSchema = new Schema
name:String
CustphoneSchema = new Schema
phone:String
subdomain:{type:ObjectId,ref :'SubdomainSchema'}
子域
字段将使用'_id'进行更新,例如:
var newSubdomain = new SubdomainSchema({name:'Example Domain'} )
newSubdomain.save()
var newCustphone = new CustphoneSchema({phone:'123-456-7890',subdomain:newSubdomain._id})
newCustphone.save( )
从子域实际获取数据
字段你将不得不使用稍微复杂的查询语法:
CustphoneSchema.findOne({})。populate( 'subdomain')。exec(function(err,custPhone){
//您的回调代码,您可以通过custPhone.subdomain.name直接访问子域名。
})
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.
It sounds like you're looking to try the new populate functionality in Mongoose.
Using your example above:
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
SubdomainSchema = new Schema
name : String
CustphoneSchema = new Schema
phone : String
subdomain : { type: ObjectId, ref: 'SubdomainSchema' }
The subdomain
field will be is updated with an '_id' such as:
var newSubdomain = new SubdomainSchema({name: 'Example Domain'})
newSubdomain.save()
var newCustphone = new CustphoneSchema({phone: '123-456-7890', subdomain: newSubdomain._id})
newCustphone.save()
To actually get data from the subdomain
field you're going to have to use the slightly more complex query syntax:
CustphoneSchema.findOne({}).populate('subdomain').exec(function(err, custPhone) {
// Your callback code where you can access subdomain directly through custPhone.subdomain.name
})
这篇关于Node.js - 用Mongoose创建关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!