简体   繁体   English

Mongoose:更新文档时转换到日期的价值失败

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

I use Mongoose in my project and in one of the schemas I use Date field, like this:我在我的项目和我使用 Date 字段的模式之一中使用 Mongoose,如下所示:

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

I can create document with this field without a problem.我可以毫无问题地使用此字段创建文档。 And when I console.log this date after it has been created I get:当我在它创建后的这个​​日期进行 console.log 时,我得到:

reservationDay:  Thu Nov 20 2014 04:45:00 GMT+0100 (CET)

However, there is a problem when I try tu update this document (even without changing reservationDay field).但是,当我尝试更新此文档时出现问题(即使不更改reservationDay 字段)。 Here is the error message I get:这是我收到的错误消息:

name: 'CastError',
  message: 'Cast to date failed for value "20/11/2014 04:11" at path "reservationDay"' } CastError: Cast to date failed for value "20/11/2014 04:11" at path "reservationDay"

Here is how I update this document on server side:以下是我在服务器端更新此文档的方法:

Reservation.findOne({ _id: id }).exec(function(err, reservation) {
                        if (err) {
                            //handle
                        }
                        if (!reservation) {
                            //handle
                        }
                        reservation = extend(reservation, req.body);
                        reservation.save(function(err, updatedReservation) {
                            if (err) {
                                //handle
                            }
                            return res.json(reservation);
                        });
                    });

and the date is not changed in the req.body.并且 req.body 中的日期没有改变。

Any ideas what might cause this error?任何想法可能导致此错误?

Thanks!谢谢!

"20/11/2014 04:11" is an invalid ISODate format. "20/11/2014 04:11"是无效的 ISODate 格式。 Somewhere you are converting reservationDate into a string of an invalid format.某处您将reservationDate 转换为无效格式的字符串。 You need to convert it to a valid ISODate format (month before day):您需要将其转换为有效的 ISODate 格式(前一天):

new Date("11/20/2014 04:11") // Thu Nov 20 2014 04:11:00 GMT+0100 (CET)
new Date("2014/11/20 04:11") // Thu Nov 20 2014 04:11:00 GMT+0100 (CET)
new Date("20/11/2014 04:11") // Invalid Date

for easy manipulation of date formats, I'd recommend using moment.js为了便于操作日期格式,我建议使用moment.js

Convert date to MongoDB ISODate format in JavaScript using Moment JS使用 Moment JS 在 JavaScript 中将日期转换为 MongoDB ISODate 格式

MongoDB uses ISODate as their primary date type. MongoDB 使用 ISODate 作为其主要日期类型。 If you want to insert a date object into a MongoDB collection, you can use the Date() shell method.如果要将日期对象插入到 MongoDB 集合中,可以使用Date() shell 方法。

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.您可以通过将包含 0 到 9999 包含范围内的年份的 ISO-8601 日期字符串传递给new Date()构造函数或 ISODate() 函数来指定特定日期。 These functions accept the following formats:这些函数接受以下格式:

  • new Date( "<YYYY-mm-dd>" ) returns the ISODate with the specified date. new Date( "<YYYY-mm-dd>" )返回具有指定日期的 ISODate。
  • new Date( "<YYYY-mm-ddTHH:MM:ss>" ) specifies the datetime in the client's local timezone and returns the ISODate with the specified datetime in UTC. new Date( "<YYYY-mm-ddTHH:MM:ss>" )指定客户端本地时区中的日期时间,并返回具有指定日期时间的 ISODate UTC 格式。
  • new Date( "<YYYY-mm-ddTHH:MM:ssZ>" ) specifies the datetime in UTC and returns the ISODate with the specified datetime in UTC. new Date( "<YYYY-mm-ddTHH:MM:ssZ>" )指定 UTC 中的日期时间并返回具有指定 UTC 日期时间的 ISODate。
  • new Date() specifies the datetime as milliseconds since the Unix epoch (Jan 1, 1970), and returns the resulting ISODate instance. new Date() 将日期时间指定为自 Unix 纪元(1970 年 1 月 1 日)以来的毫秒数,并返回结果 ISODate 实例。

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).如果您使用 JavaScript 编写代码,并且想要传递 JavaScript 日期对象并将其与 MongoDB 客户端一起使用,那么您要做的第一件事就是将 JavaScript 日期转换为 MongoDB 日期格式 (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.您可以使用 new Date() shell 方法将今天和明天的对象传递给 MongoDB 查询。

  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);
    })
  })

I would like to update one point from my mistake.我想从我的错误中更新一点。

check if you have missed leading zero for a single digit time.检查您是否错过了一位数时间的前导零。

"2017-01-01T8:00:00" is invalid and will give the mentioned error. “2017-01-01T8:00:00”无效,会出现上述错误。

"2017-01-01T08:00:00" is valid “2017-01-01T08:00:00”有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM