Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 352
Flo Avatar asked Sep 02 '18 11:09

Flo


1 Answers

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) => {
        //...
    })
like image 108
Ron537 Avatar answered Oct 16 '22 09:10

Ron537