'Why can't I get the error VersionError: No matching document found for id
I want to intentionally generate the VersionError: No matching document found for id .... error in mongoose.
Based on what I read in this question here: Mongoose - Version Error: No matching document found for id
it seems like Mongoose will try to protect against duplicate save() because it has some kind of version control.
To try to intentionally generate this error, I wrote this script:
// file: app.js
const dotenv = require('dotenv');
dotenv.config();
const mongoose = require('mongoose');
const opts = {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: true,
authSource: 'admin',
};
const schema = mongoose.Schema({
serialNumber: { type: String },
customId: { type: String },
});
const Cms = mongoose.model('Cms', schema);
const run = async () => {
try {
await mongoose.connect(process.env.MONGODB_URL, opts);
const cms1 = await Cms.findOne({});
const cms2 = await Cms.findOne({});
const randomString = new Date().toString();
cms1.serialNumber = `${randomString}AA`;
cms1.customId = `${randomString}AA`;
await cms1.save();
cms2.serialNumber = `${randomString}BB`;
await cms2.save();
} catch (e) {
console.log('err', new Date(), e.toString());
}
/* eslint-disable no-process-exit */
process.exit();
};
run();
I made sure I had exactly 1 record in my cms collection. Then I ran node app.js. I did not get any errors and I see the cms record in my mongo was updated.
I updated my run() to use a setTimeout() like this:
const run = async () => {
try {
await mongoose.connect(process.env.MONGODB_URL, opts);
const cms = await Cms.findOne();
let randomString = new Date().toString();
setTimeout(async () => {
randomString = new Date().toString();
cms.serialNumber = `${randomString}BB`;
// cms.customId = `${randomString}BB`;
await cms.save();
/* eslint-disable no-process-exit */
process.exit();
}, 2000);
cms.serialNumber = `${randomString}AA`;
cms.customId = `${randomString}AA`;
await cms.save();
} catch (e) {
console.log('err', new Date(), e.toString());
}
};
The node app.js ran successfully again and mongoose also saved the record inside the setTimeout.
How do I intentionally generate the VersionError: No matching document found for .... error? What am I missing?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
