【问题标题】:Mongoose is altering unix timestamp and converting it to UTC timeMongoose 正在更改 unix 时间戳并将其转换为 UTC 时间
【发布时间】:2017-12-17 08:24:55
【问题描述】:

我正在关注一个节点,快速教程。 这是一个补丁路线

app.patch('/todos/:id', (req, res) => {
      var id = req.params.id;
      var body = _.pick(req.body, ['text', 'completed']);

      if (!ObjectID.isValid(id)) {
        return res.status(404).send();
      }

      if (_.isBoolean(body.completed) && body.completed) {
        body.completedAt = new Date().getTime();
      } else {
        body.completed = false;
        body.completedAt = null;
      }

      Todo.findByIdAndUpdate(id, {$set: body}, {new: true}).then((todo) => {
        if (!todo) {
          return res.status(404).send();
        }

        res.send({todo});
      }).catch((e) => {
        res.status(400).send();
      })
});

这是同一路线的测试套件:

it('should update the todo', (done) => {
      var hexId = dummy[0]._id.toHexString();
      var text = 'This should be the new text';

      request(app)
        .patch(`/todos/${hexId}`)
        .send({
          completed: true,
          text
        })
        .expect(200)
        .expect((res) => {
          expect(res.body.todo.text).toBe(text);
          expect(res.body.todo.completed).toBe(true);
          expect(res.body.todo.completedAt).toBeA('number');
        })
        .end(done);
});

测试结果:
错误:预期“2017-07-12T18:38:11.814Z”是一个“数字”

最后一个测试用例失败,因为它正在从服务器接收 UTC 日期 而不是好的旧的unix时间戳。但它不应该是时间戳,因为它是 new Date().getTime() 的结果吗?
我尝试从路由中记录 body.completedAt() 和 todo.completedAt()。
body.completedAt() 正在返回一个 unix 时间戳, 而 todo.completedAt() 正在返回 UTC 时间。所以看起来猫鼬正在改变时间戳。但是我该如何防止这种情况,以便最后一个测试用例通过。
我正在使用期望断言库

【问题讨论】:

    标签: node.js express mongoose mocha.js supertest


    【解决方案1】:

    好吧,我很愚蠢,没有检查我的 mongodb 架构: 测试用例失败,因为 completedAt 的类型设置为 Date

    completedAt: {
        type: Date,
        default: null
    }
    

    应该是:

    completedAt: {
        type: Number,
        default: null
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 2012-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多