【发布时间】:2016-12-15 12:43:18
【问题描述】:
我对猫鼬很陌生,所以我可能在这里错过了一些东西。
我有两个集合“公司”和“用户”我正在尝试获取属于公司的所有用户,但公司上的用户数组返回未定义而不是我期望的用户对象。
我已通读文档并填充似乎是朝着正确方向迈出的一步,但是,它在任何阶段都没有提到(我可以看到)如何保存到我认为我需要推送对象的数组中到用户对象的 emails 属性?
我来自 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?
});
有什么想法吗?
【问题讨论】:
标签: node.js mongodb express mongoose