Mongoose query doesn't work with the filter

Viewed 592

I'm testing a nodejs snippet to do iteration with my example mongodb collection users. But the query never worked. The full users collection are printed. The standalone mongodb is setup in EKS cluster. Why the query {name: "Baker one"} didn't work?

  • The code is:

const mongoose = require("mongoose");
const url = "mongodb://xxxxxx:27017/demo";


main().catch(error => console.error(error.stack));
async function main() {

// Connect to DB
const db = await mongoose.connect(url);
console.log("Database connected!");
const { Schema } = mongoose;

// Init Model
const Users = mongoose.model("Users", {}, "users");
const users = await Users.find({name: "Baker one"}).exec();
// Iterate
for await (const doc of users) {
  console.log(doc);
  console.log("users...");
}

console.log("about to close...");
db.disconnect();

}

  • The users collection: enter image description here

  • The execution result:

$ node modify.js
Database connected!
{ _id: new ObjectId("610f512c52fa99dcd04aa743"), name: 'Baker one' }
users...
{ _id: new ObjectId("61193ed9b8af50d530576af6"), name: 'Bill S' }
users...
about to close...

1 Answers

This line could be the culprit (note that the schema has been defined with no fields like Joe pointed out in the comments).

const Users = mongoose.model("Users", {}, "users");

In this case, I had to add StrictQuery option in the Schema constructor to make it work, like so:

const userSchema = new Schema({}, { collection: "Users", strictQuery : false });
Related