2

I'm updating the mongoose version from 5 to 6 and found a change in the behavior.

This is a small example: We have two models

const MessageSchema = new mongoose.Schema({ text: String });
const Message = mongoose.model('Message', MessageSchema);

const Notification = Message.discriminator(
    'Notification',
    new mongoose.Schema({important: Boolean})
);

And let's say, we create two documents:

const m = new Message({text: 'Some text 1'});
await m.save();

const n = new Notification({important: true, text: 'Some text'});
await n.save();

And we run this query:

await Message.find({important: true})

In mongoose v5 the query will use important in spite of it not being declared in the Message schema. And the result will be just one document.

However, in the new version, it will ignore important if you query Messages, and will return all the documents, because without important query is just {}.

My question is, how can I achieve the same behavior with the new version?

I know that I could use the Notification model instead of Messages, but image if there were several models like Notification (children of Message), that had important in them, and I wanted to search in all of them.

  • Did you find an answer ? I have the exact problem .... – Sévrain CHEA May 02 '22 at 14:45
  • @SévrainCHEA I ended up just querying Notification directly. You could also try to use mongodb driver instead of mongoose model: `mongoose.connection.collections.message.findMany({important: true});` Keep in mind this will return a MongoDB cursor, instead of an array of mongoose models – Misho Tektumanidze May 03 '22 at 15:14

0 Answers0