I have more than one field in my schema to be unique, but only the last one in the schema has this constraint and sometimes no one gets the constraint and I can insert duplicated keys with no error.
@Field()
@Length(1, 50)
@prop({ trim: true, unique: true })
userName: string;
@Field()
@prop({ trim: true, unique: true })
@Length(1, 50)
identity: string;
no
did you already try the @index class-decorator?
-> these options are passed to mongoose
is this for your @ObjectType or @InputType using type-graphl ?
did you already try the
@indexclass-decorator?-> these options are passed to mongoose
Ok now it works, thank you.
@RyannGalea it's for an @ObjectType
So it's a bug or what? because I found in the documentation that I can pass the unique option to the Field decorator but it only works for one field!
@AbderrazzakB i dont know what is happening, but these options are passed to mongoose - but i will still investigate it
@AbderrazzakB i just tested it, i see no issues ...
code:
// NodeJS: 12.14.0
// MongoDB: 4.2-bionic (Docker)
import { getModelForClass, prop } from "@typegoose/typegoose"; // @typegoose/[email protected]
import * as mongoose from "mongoose"; // [email protected]
class SomeSchema {
@prop({ required: true })
public nonunique!: string;
@prop({ required: true, unique: true })
public unique1!: string;
@prop({ required: true, unique: true })
public unique2!: string;
}
const SomeModel = getModelForClass(SomeSchema);
(async () => {
await mongoose.connect(`mongodb://localhost:27017/`, { useNewUrlParser: true, dbName: "verify171", useCreateIndex: true, useUnifiedTopology: true });
const user1 = await SomeModel.create({ nonunique: "Hello1", unique1: "Hello2", unique2: "Hello3" } as SomeSchema);
console.log(user1);
const user2 = await SomeModel.create({ nonunique: "Hello1", unique1: "Hello2", unique2: "Hello3" } as SomeSchema);
console.log(user2);
await mongoose.disconnect();
})();
-> did you clear your indexes before chaning to unique | did you run model.syncIndexes? this might happen if you use something like nodemon and the collection was already created
Resulting indexes (MongoDB Compass):

@AbderrazzakB please respond in the next ~7 days, otherwise the issue will be closed
@hasezoey I'm not sure what was the problem now it's work as I expected to, thank you.
model.syncIndexes is work for me!