首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Node.js如何使用Mongoose创建关系?

Node.js如何使用Mongoose创建关系?
EN

Stack Overflow用户
提问于 2018-04-12 07:44:26
回答 2查看 0关注 0票数 0

我有2个模式CustphoneSubdomain

问题在于使用Mongoose创建关系。我的目标是执行:custphone.subdomain并获取Custphone所属的子域。

我在我的模式中有这个:

代码语言:javascript
复制
SubdomainSchema = new Schema
    name : String

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

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

代码语言:javascript
复制
{ _id: 4e9bc59b01c642bf4a00002d,
  subdomain: [] }

Custphone结果{"$oid": "4e9b532b01c642bf4a000003"}在MongoDB中时。

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

EN

回答 2

Stack Overflow用户

发布于 2018-04-12 16:30:47

这听起来像你正在试图在Mongoose中尝试新的填充功能。

使用上面的示例:

代码语言:javascript
复制
var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

SubdomainSchema = new Schema
    name : String

CustphoneSchema = new Schema
    phone : String
    subdomain  : { type: ObjectId, ref: 'SubdomainSchema' }

subdomain字段将更新为'_id',例如:

代码语言:javascript
复制
var newSubdomain = new SubdomainSchema({name: 'Example Domain'})
newSubdomain.save()

var newCustphone = new CustphoneSchema({phone: '123-456-7890', subdomain: newSubdomain._id})
newCustphone.save()

要真正从subdomain字段获取数据,将不得不使用稍微复杂一些的查询语法:

代码语言:javascript
复制
CustphoneSchema.findOne({}).populate('subdomain').exec(function(err, custPhone) { 
// Your callback code where you can access subdomain directly through custPhone.subdomain.name 
})
票数 0
EN

Stack Overflow用户

发布于 2018-04-12 17:30:56

不得不使用mongo的Model.findByIdAndUpdate()

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100004401

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档