Home > Net >  Mongoose not populating related array
Mongoose not populating related array

Time:06-26

I have followed the mongoose docs for populating related objects, everytime authSessions is empty. I can see in mongo sessions are being populated along with the related userId field. I have tried specifying ”path” and “model” options in the populate function as well but that didn’t work either. Anyone have any ideas?


//Session.js
const SessionSchema = new mongoose.Schema({
    _id: Schema.Types.ObjectId,
    sessionId: { type: String, index: true },
    createdDate: { type: Date, default: Date.now },
    revoked: Boolean,
    revokedAt: Date,
    userId: {type: Schema.Types.ObjectId, ref: 'User', index: true}
})
module.exports = mongoose.models.Session || mongoose.model('Session', SessionSchema);

//User.js
const UserSchema = new mongoose.Schema({
    _id: Schema.Types.ObjectId,
    username: { type: String, index: true },
    email: { type: String, index: true },
    password: String,
    registrationDate: { type: Date, default: Date.now },
    authSessions: [{type: Schema.Types.ObjectId, ref: 'Session'}]
})
module.exports = mongoose.models.User || mongoose.model('User', UserSchema);

const user = await User.findById(session.userId).populate('authSessions').exec();
console.log(user) //authSessions is empty

{
  _id: new ObjectId("62b6ea393e042868caa68c7d"),
  username: 'asdfasdfasdf',
  email: '[email protected]',
  password: '[email protected]',
  authSessions: [],  //empty here always
  registrationDate: 2022-06-25T10:58:01.709Z,
  __v: 0
} ```

CodePudding user response:

MongoDB, and by extension mongoose, doesn't automatically create relations for you.

If you create a Session document, you need to explicitly add it to a User document if you want populate to work:

// create a new session document and save it
const userSession = new Session(…);
await userSession.save();

// !! update the user document and save it
user.authSessions.push(userSession);
await user.save();
  • Related