Copyright ©

Mongoose OS Forum


Is it possible to query collection by value of populated field?

jameskentjameskent Poland
edited March 10 in Mongoose OS

I have collection of profiles and presence (and users)

const presenceSchema = new mongoose.Schema(
_id: { type: Schema.Types.ObjectId, ref: 'User' },
status: { type: String, required: true, lowercase: true, enum: ['online', 'offline'] }
{ collection: 'presence' });

const profileSchema = new mongoose.Schema({
_id: { type: Schema.Types.ObjectId, ref: 'User' },
username: { type: String, required: true },
presence: { type: Schema.Types.ObjectId, ref: 'Presence' }})

Is it possible to query profiles collection, populate presence, and select profiles by presence status, 'online' for example?

Something like:

  .where({'presence': {$eq: {'status': 'online'}}})

How to do it?


  • I have added:

    pre('findOne', autoPopulatePresence).
    pre('find', autoPopulatePresence);

    Now profile documents 'presence' field is either null, or object with _id and status.

    But I still can't query by 'presence' field.

    Profile.find({presence: {$ne: null}})


    .where({presence: {$ne: null}})

    doesn't work. Presence is simply ignored.


  • I made two steps workaround:

    const presenceDocs = await Presence.find();
    const presenceDocsMap = => mongoose.Types.ObjectId(doc._id));
    Profile.find({_id: {$in: presenceDocsMap}}).exec()

    I hoped for more elegant (concise) solution, but we have what we have. It looks that it's impossible to query populated fields in 'find'.
    I don't know why exactly. Yep, universe is full of mysteries :wink:

Sign In or Register to comment.