Reputation: 744
So I have 2 models, one is users
and the other is sessions
.
It was initially setup as:
const users = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
username: {type: String, unique: true},
}
);
module.exports = mongoose.model('User', users,);
I then went on and added another model, called sessions,
const sessions = mongoose.Schema({
_id: {type: mongoose.Schema.Types.ObjectId, default: mongoose.Schema.Types.ObjectId, null: false},
user_id: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
timestamp: {type: Date},
});
module.exports = mongoose.model('Sessions', sessions);
I then decided, I want to to be able to pull the user's sessions along with the users and added
sessions: [{type: mongoose.Schema.Types.ObjectId, ref: 'SurfSessions', default: null}]
to my users model schema.
I quickly learnt that users.findOne(username:admin).populate('sessions')
isn't gonna fill up sessions by itself, as sessions
returns as an empty array []
.
Since I don't have sessions
inside users
populated with objectid
's does that mean I cannot populate sessions
or is there another way?
Upvotes: 0
Views: 396
Reputation: 84
You should be able to do this with virtual populate:
const users = new mongoose.Schema(
{
_id: mongoose.Schema.Types.ObjectId,
username: { type: String, unique: true },
},
{ toJSON: { virtuals: true }, toObject: { virtuals: true } }
);
module.exports = mongoose.model('User', users);
Then:
userSchema.virtual('sessions', {
ref: 'Session', // model to search in
foreignField: 'user_id',
localField: '_id', // checks where user_id on session === _id on user
});
After this, use .populate('sessions') as normal. For more check this out: https://mongoosejs.com/docs/tutorials/virtuals.html#populate
Upvotes: 1