我有 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的子域对象。
最佳答案
听起来您想尝试 Mongoose 中的新 populate 功能。
使用上面的示例:
var Schema = mongoose.Schema,
ObjectId = Schema.ObjectId;
SubdomainSchema = new Schema
name : String
CustphoneSchema = new Schema
phone : String
subdomain : { type: ObjectId, ref: 'SubdomainSchema' }
subdomain
字段将更新为“_id”,例如:
var newSubdomain = new SubdomainSchema({name: 'Example Domain'})
newSubdomain.save()
var newCustphone = new CustphoneSchema({phone: '123-456-7890', subdomain: newSubdomain._id})
newCustphone.save()
要真正从 subdomain
字段中获取数据,您将不得不使用稍微复杂的查询语法:
CustphoneSchema.findOne({}).populate('subdomain').exec(function(err, custPhone) {
// Your callback code where you can access subdomain directly through custPhone.subdomain.name
})
https://stackoverflow.com/questions/7810892/