EugenSunic
EugenSunic

Reputation: 13703

When to use new ObjectId("string-id") over ObjectId("string-id") in Mongoose?

Since I want to be consistent with my code (Node.js)

When I have a query and need to search for something using the id value which is an unique object, what is the best way to preform it?

User.findOne({id: new ObjectId("82jf20k2k...")}...

OR

User.findOne({id: ObjectId("82jf20k2k...")}...

It seems wrong to create a new instance and filling the memory every time with objects.

The only reasonable time using new ObjectId is when data is being inserted for all other operations I would use ObjectId?

Upvotes: 3

Views: 2258

Answers (4)

kRiZ
kRiZ

Reputation: 815

I would suggest you to use Model.findById() instead of Model.findOne(_id:id), to find document based on it's _id.

You can also find more info on Mongoose Documentation.

Upvotes: 1

AJS
AJS

Reputation: 2023

You should use 2nd option i.e.

User.findOne({id: ObjectId("82jf20k2k...")}...

you are right 1st one is creating unnecessary object in memory. New keyword should be used in case you want to generate ObjectID at run time.

Upvotes: 1

Sid
Sid

Reputation: 14896

Checking the source code:

/**
* Create a new ObjectID instance
*
* @class
* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number.
* @property {number} generationTime The generation time of this ObjectId instance
* @return {ObjectID} instance of ObjectID.
*/
var ObjectID = function ObjectID(id) {
  // Duck-typing to support ObjectId from different npm packages
  if (id instanceof ObjectID) return id;
  if (!(this instanceof ObjectID)) return new ObjectID(id);

  this._bsontype = 'ObjectID';

  // more code

For what I see it is the same thing doing new or ObjectId("82jf20k2k...") as if it is not instance of ObjectID it's going to create a new instance and return it.

Upvotes: 2

Rev
Rev

Reputation: 21

you can use it like this:

User.findOne({ id: "82jf20k2k..." })

no need for "ObjectId()" as the findOne will try to convert the string to ObjectId.

Also, if you want to search documents by Id, use findById as it is more prefered.

Reference: mongoose model.js from Github

Upvotes: 1

Related Questions