var criteria = Mongoose.Types.ObjectId(payloadData.skillId)
,
when I pass incorrect Id
following error message is occured.
Error: Uncaught error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
The mongo _id
is 12-byte BSON type ObjectId
var mongoose = require('mongoose');
var id = '1111adda111';
// var id = payloadData.skillId;
console.log(mongoose.Types.ObjectId.isValid(id)); // false
var cond = mongoose.Types.ObjectId.isValid(id)
if (cond) {
// do the required operation
} else {
console.log('not a valid id');
}
Passing incorrect Mongo _id
to Mongoose.Types.ObjectId()
constructor throws BSONTypeError
which can be caught in a try catch block.
import { BSONTypeError } from 'bson';
try {
const id = Mongoose.Types.ObjectId('xyz');
}
catch {
if (e instanceof BSONTypeError) {
console.log('id is invalid');
}
else console.log('some other error');
}
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.