Extending Base but optional _id? #851
Unanswered
theDanielJLewis
asked this question in
Q&A
Replies: 1 comment 11 replies
-
read I need to set _id manually, how to do it properly?
that is either because
if you do it like in the documentation, then it should not give you a error, you can also do the Code used: // NodeJS: 19.9.0
// MongoDB: 5.0 (Docker)
// Typescript 4.9.5
import { getModelForClass, prop } from '@typegoose/typegoose'; // @typegoose/typegoose@11.2.0
import { Base } from '@typegoose/typegoose/lib/defaultClasses';
import * as mongoose from 'mongoose'; // mongoose@7.2.1
// Example from the documentation via the dual interface & class way
// eslint-disable-next-line @typescript-eslint/no-empty-interface
// interface User extends Base {}
// class User {
// @prop()
// public username?: string;
// }
// Example via the "implements" way
class User implements Base {
_id!: mongoose.Types.ObjectId;
id!: string;
@prop()
public username?: string;
}
const UserModel = getModelForClass(User);
async function main() {
await mongoose.connect(`mongodb://localhost:27017/`, {
dbName: 'verifyMASTER',
});
await UserModel.create({ username: 'hello' });
const doc = new UserModel({ username: 'user1' });
console.log(doc);
await mongoose.disconnect();
}
main(); (with the configs from typegoose-testing) |
Beta Was this translation helpful? Give feedback.
11 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm really confused and frustrated and I hope you can help!
If I extend
Base
, I can easily call_id
orid
, but any time I create a new document, TypeScript complains that_id
is required!If I try to make
_id
optional, I get the errorInterface 'MyClass' incorrectly extends interface 'Base<ObjectId>'.
But if I don't use
Base
and instead add the following to MyClass:Then the
id
value is always empty.But if I remove the
id
part, then I get errors that it doesn't exist when I try to use it instead of_id.toString()
!GAH!
Please help!
Thanks in advance!
Beta Was this translation helpful? Give feedback.
All reactions