从MongoDB的值创建新日期?

时间:2018-09-22 05:27:30

标签: node.js mongodb mongoose

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

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

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

但是它不起作用!

2 个答案:

答案 0 :(得分:0)

为什么只能使用limit时使用findOne等?

这样,您不必处理所有的数组访问等操作。find返回数组... findOne返回单个文档。

User.findOne({ title: "t" }, { time: 1, _id: 0})
  .then(function(user) {
    console.log(user.time)
  });

对于根据文档的setInterval问题:

  

setInterval()方法调用一个函数或计算一个表达式   以指定的时间间隔(以毫秒为单位)。

因此将日期以毫秒为单位new Date(val).getMilliseconds()

答案 1 :(得分:0)

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

  • 首先,val被初始化为没有值的全局变量
  • 第二,运行异步猫鼬查询,并在其回调中设置val
  • 第三次,在查询的外部/之后,将val作为参数传递来创建新日期

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

您可以通过多种方法来解决此问题,但最简单的方法是将查询后的所有代码移至查询的.then()部分,或者将查询后的所有代码包装在函数并在.then()内部调用该函数。