Mongoose: Cast to date failed for value when updating a document

前端 未结 3 571
天命终不由人
天命终不由人 2021-02-11 01:51

I use Mongoose in my project and in one of the schemas I use Date field, like this:

reservationDay: {
        type: Date,
        default: Date.now
}
         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-11 02:22

    Convert date to MongoDB ISODate format in JavaScript using Moment JS

    MongoDB uses ISODate as their primary date type. If you want to insert a date object into a MongoDB collection, you can use the Date() shell method.

    You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats:

    • new Date("") returns the ISODate with the specified date.
    • new Date("") specifies the datetime in the client’s local timezone and returns the ISODate with the specified datetime in UTC.
    • new Date("") specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC.
    • new Date() specifies the datetime as milliseconds since the Unix epoch (Jan 1, 1970), and returns the resulting ISODate instance.

    If you are writing code in JavaScript and if you want to pass a JavaScript date object and use it with MongoDB client, the first thing you do is convert JavaScript date to MongoDB date format (ISODate). Here’s how you do it.

        var today = moment(new Date()).format('YYYY-MM-DD[T00:00:00.000Z]');
        console.log("Next day -- " + (reqDate.getDate() + 1))
        var d = new Date();
        d.setDate(reqDate.getDate() + 1);
        var tomorrow = moment(d).format('YYYY-MM-DD[T00:00:00.000Z]');
    

    You can pass today and tomorrow object to MongoDB queries with new Date() shell method.

      MongoClient.connect(con, function (err, db) {
        if (err) throw err
        db.collection('orders').find({ "order_id": store_id, "orderDate": {     
           "$gte": new Date(today), "$lt": new Date(tomorrow)}
         }).toArray(function (err, result) {
            console.log(result);
            if (err) throw err
              res.send(result);
        })
      })
    

提交回复
热议问题