首页 文章

mongoose populate引用返回undefined

提问于
浏览
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?
   });

有任何想法吗?

2 回答

  • 0

    您正在将 user 推入 users 数组 . 而不是你需要 push user's Id 进入数组,即 user._id .

    Replace:

    indigoTree.users.push(user);
    

    With:

    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
       });
    

    Alternatively ,您可以使用 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(),它是一个潜在的null单文档,find()文档列表,count()文档数,update()受影响的文档数等

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

相关问题