skip to Main Content

I am writing code with node.js and mongoose module. My used module is "find" method but mongo is getting all data to me so filter is not working. What is problem ?

Example Codes:

const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/nodeV1').then(res=>console.log("Connection Success")).catch(e=>console.log("Error"))

const dbSchema = mongoose.Schema({},{collection:'users'})
const dbModel = mongoose.model('users',dbSchema)


dbModel.find({age:'28'},{age:1},(err,res)=>{
    console.log(res)
})

Result:

  { _id: new ObjectId("62eaad6af17720bd31d4daab"), age: 27 },
  { _id: new ObjectId("62eaad6af17720bd31d4daac"), age: 40 },
  { _id: new ObjectId("62eaad6af17720bd31d4daad"), age: 24 },
  { _id: new ObjectId("62eaad6af17720bd31d4daae"), age: 28 },
  { _id: new ObjectId("62eaad6af17720bd31d4daaf"), age: 20 },
  { _id: new ObjectId("62eaad6af17720bd31d4dab0"), age: 26 },
  { _id: new ObjectId("62eaad6af17720bd31d4dab1"), age: 32 },

You’r seeing data is all data arrived

What is problem ?

3

Answers


  1. You need to use the $in operator, and put the values in an array, like:

    dbModel.find({
            age: { $in:[ 28, 1] },
        },(err,res)=>{
        console.log(res)
    })
    
    Login or Signup to reply.
  2. simply update your code to this

    mongoose.connect('mongodb://localhost:27017/nodeV1').then(res => console.log("Connection Success")).catch(e => console.log("Error"))
    
    const dbSchema = mongoose.Schema({ age: Number }, { collection: 'users' })
    const dbModel = mongoose.model('users', dbSchema)
    
    dbModel.find({
        $or: [
            { age: 28 }, { age: 1 }
        ]
    }, (err, res) => {
        console.log(res)
    });
    
    Login or Signup to reply.
  3. I know it might late but if you are using latest mongoose version.
    Please read migration to 6 guide

    Plus You are searching by string on number field. Ignoring fact it might solve problem.

    Problem explained:

    dbModel.find({age:'28'})
    

    which emulates to

    dbModel.find()
    

    when you have non-existing key in query you can try one of these solutions

    // for global
    mongoose.set('strictQuery', false)
    
    // or for individual query
    await dbModel.find({ age: 28 }, null, { strictQuery: false });
    
    // or
    await dbModel.find({ age: 28 }, null, { strictQuery: false });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search