Node.js - Mongoose で関係を作成する 質問する

Node.js - Mongoose で関係を作成する 質問する

スキーマが2つあり、.aCustphoneと.SubdomainCustphone belongs_toSubdomainSubdomain has_many Custphones

問題は、Mongoose を使用して関係を作成することにあります。私の目標は、custphone.subdomain を実行し、Custphone が属するサブドメインを取得することです。

私のスキーマにはこれがあります:

SubdomainSchema = new Schema
    name : String

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

Custphone の結果を印刷すると、次のようになります。

{ _id: 4e9bc59b01c642bf4a00002d,
  subdomain: [] }

Custphone結果がMongoDBにあるとき{"$oid": "4e9b532b01c642bf4a000003"}

custphone.subdomaincustphone のサブドメイン オブジェクトを取得したいと考えています。

ベストアンサー1

新しいものを試してみたいようですね人口を増やす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 
})

おすすめ記事