Mongo - Create custom _id - node.js

So currently when one of my documents is made, Mongo generates a random ObjectId. However I would like this to be a value of my choosing. I am using postman to test this and if I create a new document and specify a value for _id then it ignores it and overwrites it with the one that Mongo generates.
I am using node to define my schema and I haven't declared an _id field, is that what I must do?

Bydefault Mongodb will generate _id of Type ObjectId ,
in mongoose if you not define _id field , it will take _id of type ObjectId
if you want to add _id field by your self , you need to define like this in your mongoose model schema
_id: {
type: Number
}

Related

define primary key myself and prevent creating the _id in mongodb

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\""}
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?
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.

How to figure out if _id field in MongDB was generate by mongo or passed by user during insert

I have an app where we pass _id to mongodb during insert instead of using the build in _id generation logic. Now in my DB I see lots of document with _id:Object('')
I need to find count of all the documents who's Id were generated by MONGO, anyone knows how??
You can use the MongoDB $type query operator.
db.collection.count({ _id: { $type: "objectId" } })

Mongoose: exclude _id field in inserts

I have a high-concurrency and parallelism situation and would like _id fields to be created by MongoDB and not by mongoose, so that I can use the ObjectId timestamps in the _id field to reliably query documents in the order they were inserted.
Is this possible? Right now I don't see how to do this with mongoose, as marking a schema with {_id: false} and trying to save it returns an error document must have an _id before saving.
Mongoose docs say the _id option only works on subdocuments, hence the error you get (http://mongoosejs.com/docs/guide.html#_id).
It might fit your situation to add a document without mongoose and in a subsequent operation update it through using mongoose (thereby keeping mongoose's Schema functionality etc).

MongoDB _id field

I'm having trouble understanding with MongoDB is doing with my documents. I have a collection of a certain document. This document has a schema (I'm using Node.js Mongoose server-side). It has a couple of arrays of sub-documents. When I save a document that does not have an _id field Mongo should generate an _id field which it does. However, some of my 'sub-documents' also seem to have been given an _id field and other types of custom sub-documents were not. What the heck is going on here? Shouldn't I just get one _id per document?

Mongoose create custom _id from other fields

I know that Mongoose populates the _id field automatically with an ObjectID if none is given and that you can overwrite the _id when constructing and instance of the model.
What I want: create the _id from other fields in a transparent way. I want to omit the _id field when creating an instance of the model and then have a function called which fills it. This function should be declared on a Schema level and whoever uses the model does not know that _id was filled by the function instead of Mongoose.
Is there a hook or a parameter of the Schema constructor I missed?
Mongoose 3.0.x
Let's make this more concrete. Imagine a BlogPost and I want to create nice URLs by slugging the title. In order to map the slug to a Mongo Object I hash the slug and turn it into a ObjectID to leverage it's benefits. Now what I'm looking for is a transparent method which allows me to create an instance of BlogPost by only passing in title and have the slug and _id property automatically generated.
use a setter on title which slugifies and idifies for you: https://gist.github.com/3658511
If you want to make sure your code is only executed once the object is created, check for this.isNew inside the setter.
Is this what you are looking for?
You could define a function to create the _id before the model is saved, as in:
http://mongoosejs.com/docs/middleware.html
If this middleware is called after Mongoose creates the _id by default (my guess is it's not), you could tell Mongoose to not create an _id, with the _id option.
http://mongoosejs.com/docs/guide.html#options

Resources