我对猫鼬来说相当新,所以我可能在这里错过了一些东西 .
我有两个集合“公司”和“用户”我试图让所有属于公司的用户但公司的用户数组返回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?
});
有任何想法吗?
2 回答
您正在将
user
推入users
数组 . 而不是你需要push
user's Id
进入数组,即user._id
.Replace:
With:
此外,
find()
查询返回array of documents
,因此您需要使用doc[0].users
,而不是doc.users
.Alternatively ,您可以使用
findOne()
而不是find()
,它返回object
. 在这种情况下,您可以使用doc.users
根据API Docs,Mongoose的
find()
返回数组而不是单个项 .