Home > Mobile >  how to query in NodeJS and Mongoose where a field equal or not equal to a value (exclude a field)
how to query in NodeJS and Mongoose where a field equal or not equal to a value (exclude a field)

Time:09-24

I am creating my rest api. I am looking for a way that I am able to find data by field which I am currently able to do. However I would also like to be able to add feature where I can get data where field does not exist.

Example:

  1. Find all records that has a uuid
  2. Find all records where title is not empty
  3. Find all records where title equal "Test Message" but description not equal "bad"
recordRouter
  .route("/templates")
  .get((req, res, next) => {
    Templates.find(req.query)
      .then(
        (record) => {
          res.statusCode = 200;
          res.setHeader("Content-Type", "application/json");
          res.json(record);
        },
        (err) => res.status(400).json(err)
      )
      .catch((err) => res.status(400).json(err));
  })
  .post((req, res, next) => {
    Templates.create(req.body)
      .then(
        (record) => {
          res.statusCode = 200;
          res.setHeader("Content-Type", "application/json");
          res.json(record);
        },
        (err) => res.status(400).json(err)
      )
      .catch((err) => res.status(400).json(err));
  })

database records

{
    "_id": {
        "$oid": "6149290b197615d32c515dab"
    },
    "instantMessage": false,
    "isComplete": true,
    "date": "2021-09-21",
    "description": "This is a test messjage v4",
    "owner": "wxTWH8zqSwaIXPAVsjZoRCkvjx73",
    "remindTime": "1630203423",
    "title": "Test Message",
    "uuid": "0Easdf-1uasdf",
    "createdAt": "2021-08-30T20:01:36.608Z",
    "updatedAt": "2021-08-30T20:01:36.608Z",
    "templateName": "my test template",
    "_ref": 1632314979,
    "__v": 0
},
{
    "_id": {
        "$oid": "614a2bf5560184026def253a"
    },
    "date": "2021-09-21",
    "title": "Test Message",
    "description": "BAD",
    "remindTime": 1632254400,
    "isComplete": true
}

CodePudding user response:

1 uuid exists :

db.collection.find({
  uuid: {
    "$exists": true
  }
})

https://mongoplayground.net/p/Yytnh__L2sS

2 title was not empty

db.collection.find({
  title: {
    "$ne": ""
  }
})

https://mongoplayground.net/p/Hko_DKKgubu

3 description not BAD and title Test Message

db.collection.find({
  description: {
    "$ne": "BAD"
  },
  title: "Test Message"
})

https://mongoplayground.net/p/qhpkOpvcaeA

all of these in and

db.collection.find({
  $and: [
    {
      description: {
        "$ne": "BAD"
      },
      title: "Test Message"
    },
    {
      title: {
        $ne: ""
      }
    },
    {
      uuid: {
        "$exists": true
      }
    }
  ]
})

https://mongoplayground.net/p/hodEeuoz17m

  • Related