Below is the code, ive also tried the $regex method, it only gives me the 'Cant use $regex' error.
let query : any;
if (data.search.length > 0) {
query = { _id: new RegExp(`^${data.search}.*`), accountId };
} else {
query = { accountId };
}
const orders: any = await TEMPOrders.find(query)
.lean()
.exec();
You can simply use ObjectId() for mongoose _id field for querying and the search value should also be an ObjectId,otherwise it will throw an error of string must be of length 12 bytes or 24 hex characters.
As _id is the primary key and it defines each documents uniquely in the collection. So ObjectId is used for comparison or for querying _id.
Import ObjectId as shown below:
var ObjectId = require('mongodb').ObjectId
query = { _id: ObjectId(data.search), accountId };
To avoid this error must convert to objectID and also add term()
var ObjectId = require(mongodb).ObjectId
var id = (req.body.id).term();
db.col.findOne({'_id':ObjectId(id)},(err,doc)=>{
if(err){
console.log(err)
}else{
console.log(doc)
}
})