-
import { getModelForClass, prop } from "@typegoose/typegoose"
import mongoose from "mongoose"
const connectDB = async () => {
await mongoose.connect("mongodb://localhost:27017/typegooseDB")
}
connectDB()
class Car {
@prop()
public color!: string
}
const CarModelA = getModelForClass(Car, { schemaOptions: { collection: "modelA" } })
const CarModelB = getModelForClass(Car, { schemaOptions: { collection: "modelB" } })
const create = async () => {
await CarModelA.create({ color: "red" })
await CarModelB.create({ color: "blue" })
}
create()
> show collections
modelA
> db.modelA.find().pretty()
{ "_id" : ObjectId("61ff93762f28003b454dd73e"), "color" : "red", "__v" : 0 }
{
"_id" : ObjectId("61ff93762f28003b454dd741"),
"color" : "blue",
"__v" : 0
}
>
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
if you want a single class to have over multiple collections, you will have to change the name of the model to be used, otherwise mongoose will only create one of the models (or overwrite the older one, i dont know how it will react) there are multiple ways to go about this:
the easiest way would be to use a different name for each model, which in typegoose can be easily done by activating |
Beta Was this translation helpful? Give feedback.
-
|
Beta Was this translation helpful? Give feedback.
-
Just to give another way: i got it working like this: export function getRepository(name: string) {
return getModelForClass(CLASSMODEL, {
schemaOptions: {
collection: name,
},
options: {
customName: () => name,
},
});
} so you've full control over the collection name |
Beta Was this translation helpful? Give feedback.
if you want a single class to have over multiple collections, you will have to change the name of the model to be used, otherwise mongoose will only create one of the models (or overwrite the older one, i dont know how it will react)
there are multiple ways to go about this:
the easiest way would be to use a different name for each model, which in typegoose can be easily done by activating
automaticName: true
and read through Typegoose's Name Generation to see how typegoose generates names