Node.js – 与Mongoosebuild立关系
我有2个Schema, Custphone和Subdomain 。 Custphone belongs_to Subdomain和Subdomain has_many Custphones 。
问题在于使用Mongoose创build关系。 我的目标是做: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.subdomain的子域对象。
这听起来像你正在试图在Mongoose中尝试新的填充function。
使用上面的例子:
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 })
我有一个类似的问题,不得不使用mongoose的Model.findByIdAndUpdate()
docs: http : //mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate
这个post也帮助了我: http : //blog.ocliw.com/2012/11/25/mongoose-add-to-an-existing-array/comment-page-1/#comment-17812