Node.js -使用Mongoose创建关系
Node.js - Creating Relationships with Mongoose
我有两个模式,Custphone
和Subdomain
。Custphone
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
相关文章:
- 如何在Parse中创建一对多关系
- 在Knockout.js模型中创建项之间的关系
- 有许多关系创建记录 - 为什么未定义
- 创建具有belongsTo关系错误的记录-Ember.js
- 如何在解析中创建嵌套的多对多关系
- Rails - 如何在创建父级时动态创建属于has_many关系一部分的成员
- 如何在续集中创建关系
- 尝试创建关系时未定义的集合
- 平均堆栈:如何为嵌套关系创建路由
- 在子对象中创建对父对象的引用是否会导致循环关系
- 我需要在两个模型(rails)之间创建一个新关系,然后通过javascript更改关系模型的属性
- 余烬数据 - 创建记录在有多重关系中
- 使用 neo4j-nodejs API 在 neo4j 中创建关系
- Parse.com 创建具有关系的对象
- 在淘汰赛中创建has_one类型关系.js
- Angular-动态创建一个新模块,并将其注入主应用程序'的依赖关系
- 插件之间的依赖关系?在创建插件之前调用方法
- 关于如何使用Mongoose创建关系的简单解释
- Node.js -使用Mongoose创建关系
- 在parse.com中使用多个类创建关系(JavaScript SDK)