0

I am trying to pull data (particularly, the memberships array) from a certain user.

_id:623db49b9da63a7758307d68
email:"test@test.com"
username:"test"
salt:"eb83e08efef62630c46b1809c7671db2109ceccff9d66862c93df1e3825c1354"
hash:"e419edb1bc481d5c87dd223a7f1dc20bece679fad1a3c1afe05dfabba341c0a9913a60..."
__v:0
memberships:Array
   0:623dc03f72436863b72c396e
   1:623dc869b61c3799494b2657

However, when I request the document, it does not retrieve the memberships portion.

{
  _id: new ObjectId("623db49b9da63a7758307d68"),
  email: 'test@test.com',
  username: 'test',
  __v: 0
}

The code below is responsible for pulling the information from the DB and then also logs what was pulled.

module.exports.showContent = async(req, res, next) => {
    try {
        const user = await User.findById(req.user.id);
        console.log(user)
        res.render('index', { user })
    } catch (e) {
        console.log(e)
        res.render('index')
    }

}

Funny enough, if there is only one ref in the array, it will show up in the console.log!

{
  _id: new ObjectId("623db49b9da63a7758307d68"),
  email: 'test@test.com',
  username: 'test',
  __v: 0,
  memberships: new ObjectId("623dc869b61c3799494b2657")
}

Schema model in question:

const UserSchema = new Schema({
    email: {
        type: String,
        required: true,
        unique: true,
    },
    username: {
        type: String,
        required: true,
        unique: true,
    },
    roles: String,
    memberships: {
        type: Schema.Types.ObjectId,
        ref: 'Community',
    },
    posts: {
        type: Schema.Types.ObjectId,
        ref: 'Posts',
    },
    comments: {
        type: Schema.Types.ObjectId,
        ref: 'Comments',
    }
})
UserSchema.plugin(passportLocalMongoose);


module.exports = mongoose.model('User', UserSchema);

My other collections do not seem to have the same issue when it comes to refs inside an array.

I have tried using .populate() to populate the data. Tried using path: and populate: within the method. Tried googling the issue, but to no luck.

Rai
  • 1
  • Use the `populate` method: `const user = await User.findById(req.user.id).populate('memberships')` – chridam Mar 25 '22 at 16:13
  • I think I had tried that earlier to no avail, but I will reattack and see if I can get further. Thanks! – Rai Mar 25 '22 at 16:43

0 Answers0