如何填充其他集合中的文档。具体案例
How to populate documents from other collection. Specific case
如何从涉及 2 个集合的查询中获取数据:
客户和地址
我需要获取所有客户的所有地址,查询客户集合。
使用 mongoose 这些是 2 个模式:
地址客户:
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);
});
});
或者:
var query = Customer.find({}).populate('address');
query.exec(function (err, customers) {
console.log('Customers: '+ customers);
});
但是customers集合中的key address没有填写。
你能告诉我如何正确设置模式和查询以获得正确的数据吗?
如何从涉及 2 个集合的查询中获取数据: 客户和地址
我需要获取所有客户的所有地址,查询客户集合。
使用 mongoose 这些是 2 个模式:
地址客户:
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);
});
});
或者:
var query = Customer.find({}).populate('address');
query.exec(function (err, customers) {
console.log('Customers: '+ customers);
});
但是customers集合中的key address没有填写。 你能告诉我如何正确设置模式和查询以获得正确的数据吗?