Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 756
Ali Nahid Avatar asked Apr 12 '26 08:04

Ali Nahid


1 Answers

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' });
like image 105
mickl Avatar answered Apr 14 '26 23:04

mickl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!