猫鼬:与引用的子文档链接的人口

时间:2014-04-17 12:56:49

标签: node.js mongodb mongoose

我必须在我的node.js express app中使用模式 - 用户和交付。

var User = new Schema({
    name: {type: String},
    addresses: [
        {
            city: {type: String},
            address: {type: String},
        }
    ],
});

我无法从交付架构的addresses字段引用用户的address子文档,因此address字段存储子文档的_id

var Delivery = new Schema({
    time: {type: String},
    address: {type: String} // this field references to User schema's address subdocument
});

那么如何在address架构中填充Delivery字段?

Delivery.findOne(/*here is condition*/).populate({path: 'address', model: 'User.addresses'});

1 个答案:

答案 0 :(得分:0)

试试这个:

var Address = new Schema({
    city: {type: String},
    address: {type: String}
});
var AddressModel = mongoose.model('AddressModel', Address);

var User = new Schema({
    name: {type: String},
    addresses: [Address],
});

var Delivery = new Schema({
    time: {type: String},
    address: {
        type: Schema.ObjectId,
        res: 'Address'
    }
});

然后:

Delivery.findOne(/*here is condition*/).populate('address')...