How do I catch error when creating a ObjectId - node.js

Im trying to create an ObjectId with mongoose in my node.js app from the parameters in the route.
If I got this route:
/product/:id
and I try to create my ObjectId for quering the product collection I use this
var o_id = moongose.Types.ObjectId(req.params.id);
But if the :id part of the route is NOT an ObjectId string, just some random text I get an error:
"Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"
How do I catch this error?
I have tried to surround o_id = moongose.Types.ObjectId(req.params.id) with try{}catch(error) {} but I get nothing in the catch expression.

The best way is to use a regex to test your expression:
if(/[a-f0-9]{24}/.test(req.params.id)) {
var o_id = moongose.Types.ObjectId(req.params.id);
}

Related

Does empty string match mongo db schema of required?

I have a mongodb schema like below.
const DemoSchema: Schema = new Schema({
demoProperty1: { type: String, required: true }
});
I create a document with syntax in node js server like below.
const savedDemo = await this.demoModel.create({demoProperty1:""});
Why it is returning error message
UnhandledPromiseRejectionWarning: ValidationError:
How to fix this issue?
From the documentation:
// Use this to allow empty strings to pass the `required` validator
mongoose.Schema.Types.String.checkRequired(v => typeof v === 'string');
Yes I have fix this issue by trial and error.
Empty string is not eligible for mongodb required schema,
Took me 5 hours to figure it out. I can just passed in any string but not an empty string to make it valid and passed without any error.

I need to be able to obtain only the string that makes up the Id in a query to MongoDB

I'm using mongoDB, mongoose and typescript and I need to keep the document ids when I query but I can only get the type _id: new ObjectId("62aa4bddae588fb13e8df552") . I only need to keep the string "62aa4bddae588fb13e8df552" to later store it and do other processing. I can't get rid of the new ObjectId
async findById(id:string) {
const convert = {"_id":id}
const userfindById = await userModel.findById(convert);
const iD = userfindById?._id
return userfindById;
}
ObjectId is just a type :
https://www.mongodb.com/docs/manual/reference/bson-types/#std-label-objectid
If you want to get the string you can extract with _id.toString(), if you want to store the string you should change the type of _id (or create a new property)

How to avoid getting "Cast to ObjectId failed for value" after passing an invalid id to a query function in mongoose?

I have a route handler that take the id parameter from request object and uses it to find a document.
I thought that the findById function would return null if it doesn't find any document with the given id. So I created an if condition which generate an error with the appropriate message and status code. But it turns out the function automatically returns the following error if the id is invalid
But I do not want the "findById" query to generate error by itself. I want the tour variable to be null if the id is invalid so that my own implementation for handling 'Not found' exception works. How may I do so?
Try wrapping the line const tour = await Tour.findById(req.params.id) with a try catch statement like this:
try {
const tour = await Tour.findById(req.params.id);
} catch (error) {
next(new AppError(error.message, 404));
}
this won't solve the problem completely as you still need to convert the value of the id you're trying to query (I assume you're receiving a string) to a mongoose ObjectId. see this answer for this

Argument passed in must be a single String of 12 bytes

mongoDB collection contains the following data
db.stack.find()
{ "_id" : "8GieRu" }
The _id is not single String of 12 bytes,
As per the MongoDB document of [ObjectID][1], id (string) – Can be a 24 byte hex string, 12 byte binary string or a Number.
Using Mongoose this collection is accessed using this Json
{"_id" : new mongoose.Types.ObjectId("8GieRu")}
and throws the below error
/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js:35
throw new Error("Argument passed in must be a single String of 12 bytes or
^
Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
at new ObjectID (/node_modules/mongoose/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js:35:11)
[1]: http://mongodb.github.io/node-mongodb-native/api-bson-generated/objectid.html
Mongoose is strictly checking the ObjectId of fixed length, how can i pass Object_id using mongoose with the given length
You mix two concepts here.
While "_id" can have any value (even subdocument like {firstName:'Foo',lastName:'Simpson'}, "ObjectId" has a fixed set of types with some restrictions, as the error message correctly states.
So your statement should be
{'_id':'putWhatEverYouWantHere'}
I had the problem in my router order:
app.get('/jobs', controllers.jobs.getAllJobs);
app.get('/jobs/karriere', controllers.jobs.getAllJobsXML);
app.get('/jobs/:id', controllers.jobs.getJob);
app.get('/jobs/:id/xml', controllers.jobs.getJobXML);
I defined /jobs/karriere after /jobs/:id so the application thought that "karriere" was an ObjectID and returned the error. The code above is the working one.
Make sure the method you are using in client and server side match. This error also shows when you have e.g. GET being sent from client side and POST required on the server side.
You are passing any
ObjectID undefinded
If the ObjectID is undfined thaen this error will come.
In my case, I'm using mongoose. and I am not able to query with something like this:
{ "_id" : "8GieRu" }
Until I bumped into my model file and specified this line counter.model.js
var CounterSchema = new Schema({
_id: String,
sequence_value: Number
})
Notice that I specified the data type as string for _id in my model.
and the, in my query, I didn't need to convert string to ObjectId.
Query now works as simple as what the filter:
{ "_id" : "8GieRu" }
same problem faced by me but after a RND . I identified that i passed wrong {Id:Undefined} so problem occured so please firstly check your Id which you passed in URL.
Error = "http://localhost:4000/api/deleteBook/Undefined"
Right = "http://localhost:4000/api/deleteBook/5bb9e79df82c0151fc0cd5c8"

find function in mongodb and literal objects

I use Mongoose on nodeJS and I have the following schema in MongoDB:
var users = new Schema({
local: {
user_uuid: String
,user_name: String
,password: String
,email: String
,connectionKey: String
}
});
And I'm exporting the schema in the following way:
module.exports.users = mongoose.model('users',users);
and this is my find statment:
var AllSchemas = require('../schemas/schemas');
...
AllSchemas.users.find({ user_uuid: doctorId},function(err,obj){
...
}
but I get that the user is not found.
If I take all the parameters out of the literal object "local" it will work
I want to know how can I find things inside a literal object.
You need to use dot notation to reach inside of embedded documents in your query:
AllSchemas.users.find({ 'local.user_uuid': doctorId }, function(err,obj) {
...
}
While referring to a sub object in the schema, you should use the dot notation inside quotes.
Please refer the following link to get the more information about the dot notation
http://docs.mongodb.org/manual/core/document/#document-dot-notation
In your case, you should use:
AllSchemas.users.find({ 'local.user_uuid': doctorId},function(err,obj){
...
}
This query will return you all the documents having user_uuid equal to doctorId.

Resources