如何从涉及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);
});
});
但客户收藏中的关键地址未填写。 你能告诉我如何正确设置模式和查询以获得正确的数据吗?