我对猫鼬相当新,所以我可能错过了这里的东西。猫鼬填充参考返回undefined
我有两个集合“公司”&“用户”我试图让所有属于公司的用户,但该公司的用户数组返回未定义,而不是我所期望的用户对象。
我已经通过文档阅读和填充似乎是在正确的方向迈出的一步,但它没有提到在任何阶段(我可以看到)如何保存到一个数组中我假设我需要推动对象到用户对象上的电子邮件属性?
我来自一个非常mysql的背景,我可能会做一些不正确的事情,如果有人可以解释一下MongoDB如何处理关系,会感激不尽。
公司架构
const companySchema = new Schema({
name: String,
slug: String,
_creator: { type: Schema.Types.ObjectId, ref: 'User' },
users: [{ type: Schema.Types.ObjectId, ref: 'User' }],
created_at: Date,
updated_at: Date
});
module.exports = mongoose.model('Company', companySchema);
用户架构的
const userSchema = new Schema({
first_name: String,
last_name: String,
username: String,
password: String,
companies: [{ type: Schema.Types.ObjectId, ref: 'Company' }],
created_at: Date,
updated_at: Date
});
module.exports = mongoose.model('User', userSchema);
保存用户
const dave = new User({
first_name: 'Dave',
last_name: 'Hewitt',
username: 'moshie',
password: '123456789',
updated_at: new Date()
});
dave.save()
.then(function (user) {
const indigoTree = new Company({
name: 'IndigoTree',
slug: 'indigotree',
_creator: dave._id,
updated_at: new Date()
});
indigoTree.users.push(user);
return indigoTree.save();
})
.then(function (company) {
console.log(company);
})
.catch(function (error) {
console.log(error);
});
检查用户
Company.find({}).populate('users').exec()
.then(function (doc) {
doc.users // undefined?
});
任何想法?