Ad

Mongoose Find Is Not Returning Array

- 1 answer

my problem is following: when I am fetching data from database (mongoose) with .find() method it fetches it but it is not returning array, instead it is returning objects separated with comma, but i need to loop through array to map it and display each result separately, and i want to know why it is not returning array and how can i convert it to array? here is my code

await Zazani.find({zaza: {$regex: req.query.keyword, $options: 'i'}})
  .skip((limit * page) - limit)
  .limit(limit)
  .exec((err,zazans)=>{
        const count = ZazanLength.length; //another fetched data for determining length 
        const pages = (Math.ceil(count / limit) == 0 ? 1 : Math.ceil(count / limit))
        res.render('search', {
            zazans,
            currentPage: page,
            totalPages: pages
        })
  }) 

and schema:

const ZazanSchema = new Schema({
   zaza: Schema.Types.String
})

and result:

{ _id: 5d6571aa4aca2d06a4bc785d, zaza: 'gela12', __v: 0 },
{ _id: 5d6572124aca2d06a4bc785e, zaza: 'gela12', __v: 0 }
...

Thank you!

Ad

Answer

await Zazani.aggregate()
  .match({zaza: {$regex: req.query.keyword, $options: 'i'}})
  .skip((limit * page) - limit)
  .limit(limit)
  .exec((err,zazans)=>{
        const count = ZazanLength.length; //another fetched data for determining length 
        const pages = (Math.ceil(count / limit) == 0 ? 1 : Math.ceil(count / limit))
        res.render('search', {
            zazans,
            currentPage: page,
            totalPages: pages
        })
  }) 

Ad
source: stackoverflow.com
Ad