Jesse
Jesse

Reputation: 303

Model.find Mongoose 6.012 always return all documents even though having filter

A sample of my schema,

const XXXSchema = new mongoose.Schema({
  name: String
}

I am using mongoose for awhile, and just recently I started experience the issues. The following query works as expected,

await MyModel.find({_id: ObjectId(SOME NUMBER)}).exec()

However, it always returns all documents if I query using any other fields, regardless value. For example,

await MyModel.find({anotherField: "some value"}).exec()

I tried to use callback, but the result is the same. Could someone help? The mongodb version I use is 5.0.2. Thanks.


Update: I reviewed mongoose query debug, and found, mongoose ignored my filter, and only send an empty {} as the filter.

Upvotes: 6

Views: 3049

Answers (4)

Paul Nadolinskyi
Paul Nadolinskyi

Reputation: 114

You can also set strict or strictQuery to false when declaring Schema.

new Schema({ field: Number }, { strictQuery: false })

Upvotes: 2

Kshitij Thakur
Kshitij Thakur

Reputation: 56

its because you don't have any field in schema named as "anotherField", Always make sure to check your find method filter field or key Name.

i.e .find({ correctFieldName: fieldValue }).

Upvotes: 3

Sai Pranav Bonthala
Sai Pranav Bonthala

Reputation: 13

I encountered this same issue after i start using Mongoose 6 version and the exact same code works in 5+ version. Below is my code where i am using a existing collection in my mongodb which will retrieve urls of Production environment based on the condition. No matter what i change it is returning all the documents and not based on the filter query. Finally i found out that from 6+ version, we need to specify the schema even though we are pointing to the existing collection in DB.

Below you can see i am using existing collection name in the model function call

const mongoose = require("mongoose");

const URLDetailsSchema = new mongoose.Schema({
      space: String // Added this change
});

const URLDetailsModel = mongoose.model(
  "URLDetailsModel",
  URLDetailsSchema,
  "uip_pcf_urls"
);

module.exports = URLDetailsModel;

This is my find call

const records = await URLDetailsModel.find({ space: "PROD" });

Upvotes: 0

Jesse
Jesse

Reputation: 303

I just found the due to a syntax error, my schema was not be used to create the corresponding model, and thus mongoose did not recognize the field I used to query.

Upvotes: 5

Related Questions