Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

208
Views
Query child model with mongoose

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.

over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!