本文介绍了Node.js - 与猫鼬建立关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个架构,CustphoneSubdomain.Custphone belongs_to SubdomainSubdomain has_many Custphones.

I have 2 Schemas, Custphone and Subdomain. Custphone belongs_to a Subdomain and Subdomain has_many Custphones.

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

The problem is in creating the relationship using Mongoose. My goal is to do: custphone.subdomain and get the Subdomain that the Custphone belongs to.

我的架构中有这个:

SubdomainSchema = new Schema
    name : String

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

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

When I print the Custphone result I get this:

{ _id: 4e9bc59b01c642bf4a00002d,
  subdomain: [] }

Custphone 结果在 MongoDB 中具有 {"$oid": "4e9b532b01c642bf4a000003"} 时.

When the Custphone result has {"$oid": "4e9b532b01c642bf4a000003"} in MongoDB.

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

I want to do custphone.subdomain and get the subdomain object of the custphone.

推荐答案

听起来您想尝试新的 populate Mongoose 中的功能.

It sounds like you're looking to try the new populate functionality in 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",例如:

The subdomain field will be is updated with an '_id' such as:

var newSubdomain = new SubdomainSchema({name: 'Example Domain'})
newSubdomain.save()

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

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

To actually get data from the subdomain field you're going to have to use the slightly more complex query syntax:

CustphoneSchema.findOne({}).populate('subdomain').exec(function(err, custPhone) {
// Your callback code where you can access subdomain directly through custPhone.subdomain.name
})

这篇关于Node.js - 与猫鼬建立关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 18:09