Automattic / mongoose

MongoDB object modeling designed to work in an asynchronous environment.
https://mongoosejs.com
MIT License
26.92k stars 3.84k forks source link

Invalid query result for embedded array #12505

Closed ammarlakho closed 1 year ago

ammarlakho commented 2 years ago

Prerequisites

Mongoose version

6.4.2

Node.js version

16.17.0

MongoDB server version

6.0.1

Description

I am facing a discrepancy in query results between mongoose and the mongsh in MongoDB Compass. The problem seems to be in the mongoose result. This is only happening when my query filter includes an embedded array.

Steps to Reproduce

These queries are being run on a MongoDB database with a collection called users with only 1 document. This is the user document:

User Document: {
  _id: ObjectId('632b4d6c1e5ae18d390f3ea4')
  businesses: [{
     firestore_id: "6f2b7632-7123-4bbd-ab0b-d0dce141cbc0"
     ...otherBusinessFields
   }
 ]
  ...otherUserFields
}
Mongoose Queries
1. userModel.findOne({'businesses.firestore_id': "6f2b7632-7123-4bbd-ab0b-d0dce141cbc0"}, {_id: 1})
    Result: { _id: ObjectId('632b4d6c1e5ae18d390f3ea4')}
2. userModel.findOne({'businesses.firestore_id': "This is an invalid id"}, {_id: 1})
    Result: { _id: ObjectId('632b4d6c1e5ae18d390f3ea4')}

Mongosh Queries
1. db.users.findOne({"businesses.firestore_id": "6f2b7632-7123-4bbd-ab0b-d0dce141cbc0"}, {_id: 1})
    Result: { _id: ObjectId("632b4d6c1e5ae18d390f3ea4") }
4. db.users.findOne({"businesses.firestore_id": "This is an invalid id"}, {_id: 1})
    Result: null

Expected Behavior

For the 2nd query findOne({"businesses.firestore_id": "This is an invalid id"}), the result should have been null, like the result for from the mongo shell.

IslandRhythms commented 2 years ago
const mongoose = require('mongoose');

const testSchema = new mongoose.Schema({
  name: String,
  businesses: []
});

const Test = mongoose.model('Test', testSchema);

async function run() {
  await mongoose.connect('mongodb://localhost:27017');
  await mongoose.connection.dropDatabase();

  await Test.create({
    name: 'Test',
    businesses: [{field: 'subField'}]
  });

  const res = await Test.findOne({ "businesses.field": "subField"})
  console.log('res', res)
  const empty = await Test.findOne({ "businesses.field": "asdf"});
  console.log('empty', empty);
}

run();
github-actions[bot] commented 2 years ago

This issue is stale because it has been open 14 days with no activity. Remove stale label or comment or this will be closed in 5 days

github-actions[bot] commented 1 year ago

This issue was closed because it has been inactive for 19 days since being marked as stale.