Search code examples
mongodbmongoosemongodb-querymongoose-schema

MongoDB Mongoose find using Map


I have a mongoose schema like this:

const userSchema = new Schema( {
    email:{ type: String, required: true, unique:true, index:true },
    mobile:{ type: String },
    phone:{ type: String },
    firstname: { type: String },
    lastname: { type: String },
    profile_pic:{type:String},
    socialHandles: {
        type: Map,
        of: String
    },
    active: {type:Boolean, default:true}
}, {
    timestamps: true
} );

I want to query "give me user where socialHandles.instagram=jondoe" how do I do it? Please help


Solution

  • Mongoose's map becomes a nested object in your database

    { "_id" : ObjectId(""), "socialHandles" : { "instagram": "jondoe" }, ..., "__v" : 0 }
    

    so you can query it by using the dot notation:

    let user = await User.findOne({ 'socialHandles.instagram': 'jondoe' });