简体   繁体   中英

Manipulate createdAt field with mongoose

For testing purposes I would like to control the createdAt field in my MongoDb object. 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.

Your test fails, because .save() is async function and you should wait for it to finish as well.

await doc2update.save();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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