Dear all =)
In the below code, I try to write a key/value test
that isn’t defined in the Mongoose schema. What I expected was to get a fatal error, but instead Mongoose just ignores that key/value. No errors thrown.
Question
How can I get Mongosse to throw an error when data doesn’t match the schema?
main().catch((err) => console.log(err));
async function main() {
const conn = await connectDb('sample_airbnb');
const ps = new mongoose.Schema({
type: String,
productNo: String,
});
const customerDocument = conn.model('customer_coll', ps);
const customerObj = new customerDocument({ type: 'bbb', test: 'aaa' });
await customerObj.validate().catch((error) => {
console.log(error);
});
await customerObj.save();
const t = await customerDocument.find({});
console.log(JSON.stringify(t, null, 2));
}
Output
]
{
"_id": "636545a81cabf00b37f5a1cc",
"type": "bbb",
"__v": 0
}
]
Hugs,
Sandra =)