我有2个模式Custphone
和Subdomain
。
问题在于使用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
并获得custphone的子域对象。
发布于 2018-04-12 16:30:47
这听起来像你正在试图在Mongoose中尝试新的填充功能。
使用上面的示例:
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
})
发布于 2018-04-12 17:30:56
不得不使用mongo的Model.findByIdAndUpdate()
https://stackoverflow.com/questions/-100004401
复制相似问题