Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find by an array property using mongoose

Products:[
  {
    name: "PSP"
    tags: ["psp","sony","videogames"]
    price: 50
  },
  {
    name: "XBOX ONE"
    tags: ["xbox","one","videogames"]
    price: 50
  },
  {
    name: "Nintendo Wii"
    tags: ["wii","nintendo","videogames"]
    price: 50
  }
]

I'm trying to filter this list by tags and I expect to get the array

mongoose.model('products').find({'Products.tags':'PSP'});

What I want is this

 {
    name: "PSP"
    tags: ["psp","sony","videogames"]
    price: 50
  }

It doesn't work!

like image 478
krlosruiz Avatar asked Feb 24 '26 13:02

krlosruiz


1 Answers

MongoDB does case-sensitive compare on strings. You're trying to find a string that's upper-case PSP but, your document contains lower-case strings psp.

You can try it like this:

mongoose.model('products').findOne({'Products.tags':'psp'}).exec(
    function(err, docs) {
        if (err) return console.error(err);
        console.log(docs.tags);
});
like image 200
Christian P Avatar answered Feb 26 '26 03:02

Christian P