Search code examples
node.jsmongodbmongoose

Mongoose Find - Exclude One Specific Document


I want to fetch many documents via Schema.find(), but exclude one specific document via its id. Currently, my query looks like:

Product
    .find({
        $or: [
            { 'tags': { $regex: criteria, $options: 'i' }, },
            { 'name': { $regex: criteria, $options: 'i' }, },
        ],
    })
    .limit(10)
    .exec((err, similar) => {
        //...
    })

I tried to add $not: { _id: someId } to the query but that gives me an error, that $not ist not valid.


Solution

  • Use $ne which stands for not equal

    Product.find({ _id: {$ne: someId}})
    

    So the whole query would look like

    Product
        .find({
            $and: [
                 { _id: {$ne: someId} },
                 { $or: [
                       { 'tags': { $regex: criteria, $options: 'i' }, },
                       { 'name': { $regex: criteria, $options: 'i' }, },
                 ]},
             ]
        })
        .limit(10)
        .exec((err, similar) => {
            //...
        })