如何填充其他集合中的文档。具体情况

时间:2017-11-27 03:22:19

标签: mongodb mongoose mongoose-populate

如何从涉及2个集合的查询中获取数据: 客户地址

我需要为所有客户提供所有地址,向客户收集查询。

使用mongoose这些是2个模式:

addressescustomers:

False

客户:

var Customer = require('./customer');

var Schema = mongoose.Schema;

var addressSchema = Schema({
    address: {
        type: String,
        required: false,
        unique: false
    },
    customer: {
        type: Schema.Types.ObjectId,
        ref: 'Customer'
    }
}, {
    timestamps: true
});

module.exports = mongoose.model('Addresscustomer', addressSchema, 'addressescustomers');

我需要向客户执行查询,我的工作是:

var Addresscustomer = require ('./addresscustomer');

var Schema = mongoose.Schema;

var customerSchema = Schema({
    name: {
        type: String,
        required: false,
        unique: false
    },
    address: {
        type: Array,
        ref: 'Addresscustomer'
    }
}, {
    timestamps: true
});

module.exports = mongoose.model('Customer', customerSchema, 'customers');

或者:

Customer.find({}, function (err, customers) {
            Addresscustomer.populate(customers, { path: "address" }, function (err, customers) {
                console.log('Customers: '+ customers);
            });
        });

但客户收藏中的关键地址未填写。 你能告诉我如何正确设置模式和查询以获得正确的数据吗?

1 个答案:

答案 0 :(得分:2)

您可以使用$lookup填充地址参考。由于Mongo 3.4 $也在数组字段上查找works

db.customers.aggregate([
    { "$lookup": {
       "from": "addressescustomers",
       "localField": "address",
       "foreignField": "_id",
       "as": "addr"
    }}
])
相关问题