In order to create a user schema using mongoose, I have the following code:
/src/server/models/User.ts:
import { model, Schema } from "mongoose";
export const UserSchema = new Schema({
address: {
type: String,
},
email: {
required: true,
type: String,
unique: true,
},
name: {
required: true,
type: String,
unique: true,
},
});
const User = model("User", UserSchema);
export default User;
To test the insertion of a user object without including the name field and return an error from mongodb, I wrote the following code:
/src/tests/db.spec.ts:
import { MongoMemoryServer } from "mongodb-memory-server";
import mongoose, { Model } from "mongoose";
import { UserSchema } from "../server/models/User";
let mongoServer: MongoMemoryServer;
const opts = {
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
};
describe("Users", () => {
let User: Model<any>;
beforeAll(async () => {
mongoServer = new MongoMemoryServer();
const mongoUri = await mongoServer.getConnectionString();
const db = await mongoose.connect(mongoUri, opts);
User = db.model("User", UserSchema);
});
afterAll(async () => {
await mongoose.disconnect();
await mongoServer.stop();
});
describe("User Creation", () => {
it("Should return an error if 'name' is missing", async () => {
const newUser = new User({
address: "address",
email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0a7f796f784a6d676b63">[email protected]</a>",
});
const createdUser = await User.create(newUser);
expect(createdUser).toThrowError("User validation failed");
});
});
});
The test failed with this error message:
● Users › User Creation › Should return an error if 'name' is missing
ValidationError: User validation failed: name: Path `name` is required.
at new ValidationError (node_modules/mongoose/lib/error/validation.js:31:11)
at model.Object.<anonymous>.Document.invalidate (node_modules/mongoose/lib/document.js:2413:32)
at p.doValidate.skipSchemaValidators (node_modules/mongoose/lib/document.js:2262:17)
at node_modules/mongoose/lib/schematype.js:1058:9
How can I resolve this issue?