0

Hi i am trying to find the documents saved D-1 day only

ISSUE: i am getting all the documents created in 24 hrs But i want to fetch them with respect to the id who has created it

//HERE IS MY CODE

exports.getPreviousDayOrder = async (req,res,next) =>{
   vendorId=req.params.id
   let d= new Date()
   let pdate =d.getDate()-2
   let month = d.getMonth()+1
   let year = d.getFullYear()
  previousDay= `${year}-${month}-${pdate}T00:00:00.000Z`
  currentDay= Date.now

   const vendorOrder = await Order.find({vendorId,createdDate:{$gt:previousDay},$lt:currentDay})
      try {
          if (!vendorOrder) {
            const error = new Error('Could not find Order.')
            error.statusCode = 404;
            throw error;
          }
          res.status(200).json({message:'VendorOrder fetched.',vendorOrder})
        }  catch(error) {res.send(error)}
             next(error)
        }

HERE IS THE RESPONSE I'M GETTING FROM THE POSTMAN--an empty document

{
    "message": "VendorOrder fetched.",
    "vendorOrder": []
}

Other Queries which i have tried

const vendorOrder = await Order.find({createdDate:{$gt:previousDay},$lt:currentDay})

it is giving all the documents with every vendors id created on D-1 day

If i remove :/id from my route then i am getting all the documents with the logged in id as token authentication is there.

RamPrakash
  • 1,687
  • 3
  • 20
  • 25
sachin
  • 103
  • 8

1 Answers1

0

This assumes that vendorId is the id of a document in MongoDB. You will need to cast the id using ObjectId(...). Also the try/catch needs to contain the find, otherwise database errors won't be caught.

try{
  const vendorOrder = await Order.find({
      vendorId:mongoose.Types.ObjectId(req.params.id),
      createdDate:{$gt:previousDay},
      createdDate:{$lt:currentDay}
  })
  if (!vendorOrder) {
    const error = new Error('Could not find Order.')
    error.statusCode = 404;
    throw error;
  }
  res.status(200).json({message:'VendorOrder fetched.',vendorOrder})
}  
catch(error) {res.send(error);next(error)}

Some more examples here: https://stackoverflow.com/a/38455992/238847

MondoDB ObjectID: https://mongodb.github.io/node-mongodb-native/2.0/tutorials/objectid/

Stan Wiechers
  • 1,962
  • 27
  • 45
  • Thanks Stan , i tried your answer but its returning empty documents, i think there is some mismatch the way i am querying Date from nodejs vs the date which is getting saved in Mongo, if you can suggest anything – sachin Dec 28 '19 at 11:23