简体   繁体   English

用猫鼬操纵createdAt字段

[英]Manipulate createdAt field with mongoose

For testing purposes I would like to control the createdAt field in my MongoDb object. 出于测试目的,我想控制createdAt在我的MongoDB的对象字段。 Unfortunately I'm afraid that this isn't possible with standard timestamp implementation. 不幸的是,我担心使用标准时间戳实现是不可能的。 Here's the gist of the code that I'm using to create some objects and then setting their created timestamp: 这是我用来创建一些对象然后设置其创建的时间戳的代码的要点:

const docArray = [];
const times = [15, 32, 1233, 122].map(seconds => moment().add(seconds, 'seconds'));

for (let i = 0; i < times.length; i += 1) {
  // Create an object
  docArray.push(await createObj(`${i}`));

  const doc2update = await MyModel.findById(docArray[i]._id);
  // Save the original created date
  const org = doc2update.createdAt;

  // Do the update
  doc2update.createdAt = times[i];
  doc2update.save(); // tried doc2update.update() without change

  // Retrieve the updated object
  docArray[i] = await TaskModel.findById(docArray[i]._id);

  // Check if change preserved
  console.log(docArray[i].createdAt - org,
              'vs expected',
              doc2update.createdAt - org);
}

The output is rather disappointing 输出相当令人失望

0 'vs expected' 14841
0 'vs expected' 31809
0 'vs expected' 1232787
0 'vs expected' 121762

I guess that manipulating created in this way is not recommended for regular use but it would convenient when testing. 我猜想不建议常规使用这种方式创建的操作,但是在测试时会很方便。 Is there a way around this? 有没有解决的办法?

You can manipulate timestamp in mongoose , just like any other value in your document. 您可以使用mongoose操纵时间戳记 ,就像文档中的任何其他值一样。

Your test fails, because .save() is async function and you should wait for it to finish as well. 您的测试失败,因为.save()是异步函数,您还应该等待它完成。

await doc2update.save();

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

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