Home > Software engineering >  Nodejs express filter data by query
Nodejs express filter data by query

Time:09-11

I need to run the query by find like I pass id and data only with that Id will display but the issue is it's showing all data means it's not filtering.

I am finding data like this

router.get('/getannouncementsbyrestaurant/:id', async (req, res) => {

    let getannouncementsbyrestaurant = await Announcements.find({ restaurants: req.params.id }).populate(['announcementRestaurants']);
    if (!getannouncementsbyrestaurant) {
        return res.status(400).json({ success: false, message: "something went wrong" })
    }
    res.status(200).json({ success: true, data: getannouncementsbyrestaurant })

})

and here is the model

const mongoose = require('mongoose');

const announcementsschema = new mongoose.Schema({

    announcementName: {
        type: String,
        required: true
    },
    announcementDescription: {
        type: String,
        required: true
    },
    announcementCountry: {
        type: String,
        required: false
    },
    announcementCity: {
        type: String,
        required: false
    },
    announcementStreet: {
        type: String,
        default: ''
    },
    announcementRestaurants: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'restaurants'
    },
    announcementCreatedOn: {
        type: Date,
        default: Date.now
    }




})

announcementsschema.virtual('id').get(function () {
    return this._id.toHexString();
});

announcementsschema.set('toJSON', {
    virtuals: true,
});
exports.Announcements = mongoose.model('Announcements', announcementsschema);
exports.announcementsschema = announcementsschema;

Don't know why its showing all data

here is example json

  "data": [
    {
      "_id": "631a4c9c2c4fca7afc0f23f5",
      "announcementName": "Mega Sale 10% off",

      "announcementRestaurants": {
        "_id": "631a4af62c4fca7afc0f238f",
        "restaurantName": "Mega Restaurant",
  
      },
      "id": "631a4c9c2c4fca7afc0f23f5"
    },
    {
      "_id": "631a51b72c4fca7afc0f2449",
      "announcementName": "Sale upto 90%",

      "announcementRestaurants": {
        "_id": "631a51752c4fca7afc0f2434",
        "restaurantName": "McDonalds",
      
      },
      "announcementCreatedOn": "2022-09-08T20:33:59.870Z",
      "__v": 0,
      "id": "631a51b72c4fca7afc0f2449"
    }
]

I am passing announcementRestaurants._id in param and need to filter with that.

CodePudding user response:

Your schema doesn't have the field restaurants. The corresponding field is announcementRestaurants. So the query should be:

let getannouncementsbyrestaurant = 
await Announcements.find({ announcementRestaurants: req.params.id }).populate(['announcementRestaurants']);

Or

let getannouncementsbyrestaurant = 
    await Announcements.find({ announcementRestaurants: mongoose.Types.ObjectId(req.params.id) }).populate(['announcementRestaurants']);
  • Related