Home > Software design >  Is it possible to query a element in mongoose map by key alone
Is it possible to query a element in mongoose map by key alone

Time:10-29

If I have a mongoose schema with a map. Is it possible to query a element in the map by key alone

const userSchema = new Schema( {
    
    socialHandles: {
        type: Map,
        of: String
    },
    active: {type:Boolean, default:true}
} );

I am able to query and find a user whose social handles has instagram key and instagram key holds a particular value with the below syntax.

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

I am looking for a way to query and find the instagram ids of user if a key called instagram exists. Something of the below form ie get a user with a social handle instagram ( I would need the value of instagram later on).

let user = await User.findOne({ 'socialHandles.instagram': * });  // this is just a wrong syntax to explain what I want to achieve

CodePudding user response:

Use exists

let user = await User.findOne().exists('socialHandles.instagram')

CodePudding user response:

You can use $exists like this:

User.findOne({
  "socialHandles.instagram": {
    "$exists": true
  }
})

Example here

  • Related