【问题标题】:mongoose populate reference returns undefined猫鼬填充参考返回未定义
【发布时间】: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


    【解决方案1】:

    您正在将user 推入users 数组。而不是你需要将push user'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
       });
    

    【讨论】:

      【解决方案2】:

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

      对于 findOne() 它是一个可能为空的单个文档,find() 是文档列表,count() 是文档数,update() 是受影响的文档数,等等

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-13
        • 2021-04-15
        • 2017-09-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-05
        • 1970-01-01
        相关资源
        最近更新 更多