how necessary is it to use ObjectId? #11471
-
|
I'm seeing stuff like this being used all over a project i started to help out in: const ObjectId = require('mongoose').Types.ObjectId
const someModel = require('../userModel.js')
function handle (req, res) {
await someModel.find({ _id: ObjectId(req.body.id) })
}it's quite bloated. it seems perfectly fine to do: so my question is how often do you need to use ObjectId and when is it okey to just use a string? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
As long as await someModel.find({ _id: req.body.id });By default, schemas have an Mongoose casts query filters to match your schema, so it can do things like convert strings to numbers or strings to ObjectIds: https://mongoosejs.com/docs/tutorials/query_casting.html |
Beta Was this translation helpful? Give feedback.
As long as
_idis an ObjectId inuserModel's schema, you shouldn't have to doObjectId(). The below should be fine:By default, schemas have an
_idof type ObjectId. So if there's no_idinuserModel's schema, the above code should still work.Mongoose casts query filters to match your schema, so it can do things like convert strings to numbers or strings to ObjectIds: https://mongoosejs.com/docs/tutorials/query_casting.html