These are chat archives for Automattic/mongoose

13th
Oct 2018
Haydar Al-Rikabi
@haydaralrikabi
Oct 13 2018 14:45

Hi,
I am getting an error "isValid is not a function" when I run the following code:

mongoose.Types.ObjectId().isValid(req.params.id)

Can anyone help please!!

Kev
@lineus
Oct 13 2018 14:58

@haydaralrikabi mongoose.Types.ObjectId() returns a new instance of an ObjectId, but isValid isn't defined on the prototype so instances of BSON ObjectIds don't have an isValid method.

You can do this instead: mongoose.Types.ObjectId.isValid(req.params.id)

note that I'm not calling mongoose.Types.ObjectId i.e. I removed the () from ObjectId
#!/usr/bin/env node
'use strict';

const mongoose = require('mongoose');

const str1 = 'f'.repeat(24);
const str2 = 'g'.repeat(24);

function testForValidId(str) {
  return mongoose.Types.ObjectId.isValid(str);
}

console.log(testForValidId(str1));
console.log(testForValidId(str2));
outputs:
gitter: ./haydar.js
true
false
gitter: