スキーマが2つあり、.aCustphone
と.Subdomain
Custphone
belongs_to
Subdomain
Subdomain
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.subdomain
custphone のサブドメイン オブジェクトを取得したいと考えています。
ベストアンサー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
})