Node.js -使用Mongoose创建关系

Node.js - Creating Relationships with Mongoose

本文关键字:创建 关系 Mongoose 使用 js Node      更新时间:2023-09-26

我有两个模式,CustphoneSubdomainCustphone belongs_to a Subdomain and Subdomain has_many Custphones .

问题是在使用Mongoose创建关系时。我的目标是做:客户电话。子域,获取客户电话所属的子域。

我在我的模式中有这个:

SubdomainSchema = new Schema
    name : String
CustphoneSchema = new Schema
    phone : String
    subdomain  : [SubdomainSchema]

当我打印Custphone结果时,我得到这个:

{ _id: 4e9bc59b01c642bf4a00002d,
  subdomain: [] }

当MongoDB的Custphone结果有{"$oid": "4e9b532b01c642bf4a000003"}

我想做custphone.subdomain并获得custphone的子域对象

听起来你想尝试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 
})

我有一个类似的问题,不得不使用mongoose的Model.findByIdAndUpdate()

文档:http://mongoosejs.com/docs/api.html model_Model.findByIdAndUpdate

这篇文章也帮助了我:http://blog.ocliw.com/2012/11/25/mongoose-add-to-an-existing-array/comment-page-1/#comment-17812