2016-12-15 114 views
0

我对猫鼬相当新,所以我可能错过了这里的东西。猫鼬填充参考返回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? 
    }); 

任何想法?

回答

0

您正在将user推入users阵列。而不是你需要pushuser's Id进入阵列,即user._id

替换:

indigoTree.users.push(user); 

有了:

indigoTree.users.push(user._id); 

此外,find()查询返回array of documents,所以你需要使用doc[0].users,不doc.users

Company.find({}).populate('users').exec() 
    .then(function (doc) { 
     doc[0].users // undefined? -> change here, it wont come undefined 
    }); 

或者,您可以使用findOne()代替find(),它返回一个object。在这种情况下,您可以使用doc.users

Company.findOne({_id: someCompanyId}).populate('users').exec() 
    .then(function (doc) { 
     doc.users // it wont come undefined 
    }); 
0

根据API Docs,Mongoose的find()返回一个数组集合,而不是单个项目。

对于findOne()这是一个潜在的空单文档,找到()的文件清单,计数()的文件数量,更新()受影响的文件数量等

Company.find({}).populate('users').exec().then((doc) => { 
    console.log(doc[0].users); // prints users array 
});