Подтвердить что ты не робот

Node.js - Создание отношений с Mongoose

У меня есть 2 схемы, Custphone и Subdomain. Custphone belongs_to a 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 имеет {"$oid": "4e9b532b01c642bf4a000003"} в MongoDB.

Я хочу сделать custphone.subdomain и получить объект субдомена custphone.

4b9b3361

Ответ 1

Похоже, вы хотите попробовать новую функциональность populate в 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 
})