These are chat archives for Automattic/mongoose

Oct 2018
Alex Luong
Oct 28 2018 01:18

Hi. I wonder how I can query with Map type. For example, say I have a schema like

const ParticipantSchema = new mongoose.Schema({
  userId: ObjectId,
  name: String,

const ConversationSchema = new mongoose.Schema({
  participants: {
    type: Map,
    of: ParticipantSchema,

This query doesn't work:

const conversations = await Conversation.find({ "participants.userId": userId })

Am I missing something? Thanks.

Oct 28 2018 12:02
@alexluong Map values in mongoose must have unique string keys because the data gets stored in the db as a BSON object. Each object of ParticipantSchema you add to the Map will also have a key, e.g. doc.participants.set('stringKey', { userId: 'f'.repeat(24), name: 'Billy' }). There isn't a userId field directly under participants, it would be participants.stringKey.userId. Here's an example gist
Oct 28 2018 13:27
@alexluong Since Maps require unique string keys, you could slightly change the shape of the Map subdocuments, using the userId as the key. This would allow you to query based on whether the field you're looking for exists. Example gist here