Home > database >  define primary key myself and prevent creating the _id in mongodb
define primary key myself and prevent creating the _id in mongodb

Time:03-19

I am two questions: 1- I want get by Id from database but operation is based on the key that is made automatically by MangoDB e.g _id. I want to search based on a field that I created myself e.g: id. for this porpouse I used following :

app.get('/:id',async(req,res)=>{
    try{
        const get=await product.findById({id:req.params.id});
        res.json(get);
    }
    catch(err){
        res.send(err);
    }
});

and get following output:

{"stringValue":"\"{ id: '1' }\"","valueType":"Object","kind":"Number","value":{"id":"1"},"path":"_id","reason":{"generatedMessage":true,"code":"ERR_ASSERTION","actual":false,"expected":true,"operator":"=="},"name":"CastError","message":"Cast to Number failed for value \"{ id: '1' }\" (type Object) at path \"_id\" for model \"product\""}
  1. when creating the database the fied _id is created by mongodb and know as key. What command should I use to prevent this field from being created? how do i define key field myself in database or select my own definition field as the primary key on which to search?

CodePudding user response:

If you want to do that, you should use find method:

const get = await product.find({id:req.params.id});

I'm not sure, but I think that is not possible to avoid the creation of field _id in mongodb, although you can avoid the ObjectId type if you specify the field _id with a custom value (should be unique) when you insert the document.

But if you want to use a custom id value, you will need to use mongoose find method by you custom id as I indicated before. Since your custom id field should be unique you can use findOne in order to improve the performance of the query.

  • Related