question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

possible bug: SchemaTypes.ObjectId.cast does not run when value is `null`

See original GitHub issue

So, I came across a case where I want to set all object ids to be undefined if the value passed to document is null. The reason being that I want to avoid having null keys in my documents, and prefer not having them altogether.

However, trying to do that via custom casting logic did not work because the cast function is not invoked when the value is null.

'use strict';
disallowNullInObjectId();

// does not work
function disallowNullInObjectId () {
  const originalObjectIdCast = mongoose.SchemaTypes.ObjectId.cast();

  mongoose.SchemaTypes.ObjectId.cast(function (value) {
    if (value === null) {
      return undefined;
    }
    return originalObjectIdCast(value);
  });
}



const userSchema = new Schema({
  name: { type: String },
  cityId: Schema.ObjectId
});

const User = mongoose.model('User', userSchema);

const user = new User({ name: 'Hafez', cityId: null });

// fails, user.cityId is `null` instead of `undefined`
assert.strictEqual(user.cityId, undefined);

I was able to work around this by setting a default set value to all object ids.

// works
function disallowNullInObjectId () {
  mongoose.SchemaTypes.ObjectId.set('set', (value) => {
    if (value === null) {
      return undefined;
    }

    return value;
  });
}

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:1
  • Comments:10

github_iconTop GitHub Comments

1reaction
vkarpov15commented, Dec 3, 2020

We explicitly avoid casting nullish values with this line: https://github.com/Automattic/mongoose/blob/b9dd74b3a9f9b9237d40a16fe6f4b28da9ee60fb/lib/schematype.js#L1105-L1107 . Whether we continue doing this is something worth discussing. I think the general idea is that cast functions shouldn’t always have to write if (v == null) { return v }, but I can see arguments on both sides. What do you think @AbdelrahmanHafez ?

The current workaround is to use a setter as you described.

0reactions
vkarpov15commented, Dec 4, 2022

Yeah, global schematype validation: https://mongoosejs.com/docs/validation.html#global-schematype-validation mongoose.Schema.ObjectId.set('validate', v => v !== null)

Read more comments on GitHub >

github_iconTop Results From Across the Web

node.js - Cast to ObjectId failed for value ...
Seems like it's working just fine as it is. You don't need to change a thing in it!!! One issue though, look at...
Read more >
Mongoose v6.8.2: SchemaTypes
ObjectId SchemaType doesn't actually create MongoDB ObjectIds, ... ObjectId, decimal: Schema.Types. ... The values null and undefined are not cast.
Read more >
Automattic/mongoose - Gitter
Is there a way to connect a GCP Firestore / Firebase NoSQL database to a mongooose layer? We are using nestjs with mongoose...
Read more >
mongoose cast to objectid failed for value - You.com
ObjectId. Mongoose (but not mongo) can accept object Ids as strings and "cast" them properly for you, so just use: MyClass.findById(req.params.id).
Read more >
Database Engine events and errors - SQL Server
Consult this MSSQL error code list to find explanations for error messages for SQL ... 127, 15, No, A TOP N value may...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found