Answer a question

Just tried MongoDB and Mongoose, so I'm a bit lost. How can I check if field exists and if it does, check it against a value? This is what I've got so far. The way it's queried is just like that for the existing ones.

By the way, the goal of the query is to pull all records that has not been tagged as isDeleted true and should support pre-existing records that does not have isDeleted field when it was created prior to isDeleted implementation.

With the query below, I get this error:

Cast to Boolean failed for value "[ { '$exists': false }, { '$ne': true } ]" at path "isDeleted" for model...

query.isDeleted = {
        $or: [
          { $exists: false },
          { $ne: true }
        ]
      };

return this.find(query)
      .exec();

Alernative answer (if you don't want to add a property to query variable like the way above):

const isNotDeleted = {
    $and: [
       { $or:
           [
             { isDeleted: { $exists: false } },
             { isDeleted: { $eq: false } },
           ],
       },
    ],
};

const query = {
      ...otherQuery,
      ...isNotDeleted,
    };

return this.find(query).exec();

Answers

As the error suggests the position of your $or is wrong you can do it like this

query.$or = [
          {isDeleted: { $exists: false }},
          {isDeleted: { $ne: true }}
        ];

return this.find(query)
      .exec();

MongoDB $or reference

In your case isDeleted: Boolean but you're checking it against an Object which is {$or: []} that's why you get a type error.

Logo

MongoDB社区为您提供最前沿的新闻资讯和知识内容

更多推荐