don*_*ald 59 javascript mongoose mongodb node.js
我有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]
Run Code Online (Sandbox Code Playgroud)
当我打印Custphone结果时,我得到了这个:
{ _id: 4e9bc59b01c642bf4a00002d,
subdomain: [] }
Run Code Online (Sandbox Code Playgroud)
当Custphone结果出现{"$oid": "4e9b532b01c642bf4a000003"}在MongoDB中时.
我想做custphone.subdomain并获得custphone的子域对象.
Dan*_*Dan 125
听起来你正在寻找在Mongoose中尝试新的填充功能.
使用上面的示例:
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
SubdomainSchema = new Schema
name : String
CustphoneSchema = new Schema
phone : String
subdomain : { type: ObjectId, ref: 'SubdomainSchema' }
Run Code Online (Sandbox Code Playgroud)
该subdomain字段将使用'_id'进行更新,例如:
var newSubdomain = new SubdomainSchema({name: 'Example Domain'})
newSubdomain.save()
var newCustphone = new CustphoneSchema({phone: '123-456-7890', subdomain: newSubdomain._id})
newCustphone.save()
Run Code Online (Sandbox Code Playgroud)
要从subdomain字段中实际获取数据,您将不得不使用稍微复杂的查询语法:
CustphoneSchema.findOne({}).populate('subdomain').exec(function(err, custPhone) {
// Your callback code where you can access subdomain directly through custPhone.subdomain.name
})
Run Code Online (Sandbox Code Playgroud)