首页 > 解决方案 > 从 MongoDB 的值创建新日期?

问题描述

我的程序使用 nods.js 在服务器端运行

我从 mongodb 获取日期值作为日期格式:

 User.find({ title: "t" }, { time: 1, _id: 0 })
 .limit(1)

这是我的 mongodb 架构:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const UserSchema = new Schema({
  title: {
    type: String
  },
  des: {
    type: String
  },
  min: {
    type: Number
  },
  st: {
    type: Number
  },
  time: {
    type: Date
  },
  image: {
    data: Buffer,
    contentType: String
  }
});

const User = mongoose.model("user", UserSchema);

module.exports = User;

这是我的完整代码:

var v = new Date();
var n;
var val;
var s;
var c;
//getting the value from mongodb 
User.find({
    title: "t"
  }, {
    time: 1,
    _id: 0
  })
  .limit(1)
  .then(function(user) {
    v = user;
    n = v[0];
    val = n["time"];
    s = String(val);
    //var w = Object.assign({ time }, n);
    console.log(v);
    console.log(n);
    console.log(val);
    console.log(s);
    console.log();
  });


//count down timer:
var countDownDate = new Date(val);
console.log(countDownDate);

// Update the count down every 1 second
var x = setInterval(function() {
  // Get todays date and time
  var now = new Date();

  // Find the distance between now an the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 *
    60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Output the result in an element with id="demo"
  console.log(days, hours, minutes, seconds);
}, 1000);

我不能用它来启动我的计时器!!如果我这样写:

 var countDownDate = new Date(val);

当我在参数中写入与 String 相同的值时,它工作正常,如下所示:

var countDownDate = new Date("Fri May 24 2019 10:30:00 GMT-0700 (PDT)");

如何在不显示“NaN”的情况下将变量 val 传递给 countDownDate ?我尝试使用以下方法将 val 转换为 String:

 s = String(val);

但它不起作用!

标签: node.jsmongodbmongoose

解决方案


原因countDownDate分配不正确并new Date(val)返回NaN是因为:

  • 一、val被初始化为没有值的全局变量
  • 二、运行异步Mongoose查询,并val在其回调中设置
  • 第三,在查询之外/之后,val作为参数传递以创建新日期

这里的关键是因为 Mongoose 查询/回调是异步的,所以步骤 #3 实际上是在步骤 #2之前执行的。这意味着,因为val最初没有值,所以传递的是新日期undefined而不是时间或日期字符串。

有很多方法可以解决这个问题,但最简单的方法是将查询之后的所有代码移动到查询的.then()一部分中,或者只是将查询之后的所有代码包装在一个函数中,然后在内部调用该函数.then()


推荐阅读