Home > Mobile >  Mongoose Filter Not Working With Find Method
Mongoose Filter Not Working With Find Method

Time:08-04

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 ?

CodePudding user response:

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)
})

CodePudding user response:

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)
});
  • Related