user13613988
user13613988

Reputation:

Mongoose populate referencing object id, not the object itself

Background

Here's part of my User model:

const Group = require("./Group")

...

groups: {
    type: [{ type: Schema.ObjectId, ref: Group }],
    default: [],
},

And here's my Group model:

module.exports = mongoose.model(
    "Group",
    new Schema(
        {
            name: {
                type: String,
                required: true,
                unique: true,
            },

            /**
             * Array of User ObjectIDs that have owner rights on this group
             */
            owners: {
                type: [{ type: Schema.ObjectId, ref: User }],
                default: [],
            },
        },
        {
            timestamps: true,
        }
    )
)

The Code

Here's the code I'm running to try and populate:

const user = await (await User.findOne({ _id: ... })).execPopulate("Group")
console.log(user.groups)

My console.log is outputting an array of object IDs, when I'd like it to output an actual Group document.

Attempted solutions

I've tried changing my ref to be using the string ("Group"), I've tried arranging my query differently, etc. I'm not sure how I'd go about doing this.

Apologies in advance if this is a duplicate, I've done my best to search but can't really find a solution that works for me.

Specifically, what do I need help with?

I'm trying to create a 'link' between a user model and a group model. In my console.log, I expect it to output a Group document; but it outputs an object ID (which is how it's stored raw in the database, meaning that Mongoose isn't transforming it correctly)

Upvotes: 0

Views: 699

Answers (1)

Rômulo Rocha
Rômulo Rocha

Reputation: 61

When you change execPopulate to populate like:

async function findUserAndPopulate(userId){
  const response = await User.findOne({
    _id: userId,
  }).populate('groups')


  console.log("response",response)
}

You got:

{
  groups: [
    {
      owners: [Array],
      _id: 5ecc637916a2223f15581ec7,
      name: 'Crazy',
      createdAt: 2020-05-26T00:31:53.379Z,
      updatedAt: 2020-05-26T00:31:53.379Z,
      __v: 0
    }
  ],
  _id: 5ecc6206820d583b99b6b595,
  fullname: 'James R',
  createdAt: 2020-05-26T00:25:42.948Z,
  updatedAt: 2020-05-26T00:36:12.186Z,
  __v: 1
}

So you can access the user.groups

See the doc: https://mongoosejs.com/docs/populate.html

Upvotes: 1

Related Questions