If i have a mongo document id as a string how do I query for it as an _id?
Will it work correctly to do .find({_id:'stringID'})
or do I need to convert it to a bson object first?
Yes, you can. BTW, uniqueness guaranteed by mongodb. Because _id field has a unique index by default.
To query data from MongoDB collection, you need to use MongoDB's find() method.
Use the $text query operator to perform text searches on a collection with a text index. $text will tokenize the search string using whitespace and most punctuation as delimiters, and perform a logical OR of all such tokens in the search string.
Mongoose & MongoDB provide a very useful function in ObjectId i.e. ObjectId. isValid(“some_id”) to validate a string for correct MongoDB ID.
If your _id values are strings, you may query them just like any other field. (Just remember, if you are setting custom values for _id, they must be kept unique, or you will get a duplicate key error. )
Here is an example in the Mongo JS Shell:
> db.test.insert({_id:"stringID1"})
> db.test.insert({_id:"stringID2"})
> db.test.insert({_id:"stringID3"})
> db.test.find({_id:"stringID1"})
{ "_id" : "stringID1" }
>
Is this what you were looking for? I hope I did not misunderstand your question!
Mongoose auto casts the string _id
to ObjectId when you use findByID
, so you can query using the string _id
.
Also remember that any input coming into your API from req.body
or req.params
will all be type string so you will need to type cast if needed..., but as mentioned, mongoose does that for you so you can just leave _id
in the string format it comes in as.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With