1
votes

When I convert a string to ObjectId, I use

import * as mongoose from 'mongoose';

const objId = mongoose.Types.ObjectId(strId);

It works well in TypeScript 1.x, after updating to TypeScript 2.x, I got the error:

error TS2348: Value of type 'typeof ObjectID' is not callable. Did you mean to include 'new'?

How can I solve it? Thanks

2
How about using new? Should be as simple as: const objId = new mongoose.Types.ObjectId(strId);Nitzan Tomer
@NitzanTomer Wow, I remembered I tried it before but failed, but now it works well! Would u mind moving to answer?Hongbo Miao

2 Answers

5
votes

The mongoose docs show that you can instantiate ObjectId without the new keyword, but the typescript definitions (at least the ones I've seen, like the one on DefinitelyTyped) don't have that, so if you want to avoid typescript compilation errors you'll need to use the new keyword:

const objId = new mongoose.Types.ObjectId(strId);

You should also be able to do something like:

type ObjectIdConstructor = {
    (str: string): mongoose.Types.ObjectId;
    new (str: string): mongoose.Types.ObjectId;
}

const objId = (mongoose.Types.ObjectId as ObjectIdConstructor)(strId);
0
votes

It should be mongoose.Schema.Types.ObjectId instead of mongoose.Types.ObjectId.