I'm trying to create a new record using data from the request body. The request body data looks like this:
{
extras: [{value: "string"}, {value: "string"}, {value: "string"}],
skills: [{value: "string"}, {value: "string"}]
}
These properties contain lists of objects. To create a new record in my post request handler, I'm using the following code:
const record = new Record(req.body);
try {
const newRecord = await record.save();
res.status(200).json(newRecord);
} catch (err) {
res.status(400).json({ message: err.message });
}
However, my Mongoose schema expects these properties to be lists of strings. To convert the object values to strings before saving the record to the database, I've added a pre-validate hook. Here's my code:
const recordSchema = new Schema(
{
extras: [String],
skills: [String]
},
{
timestamps: true
}
)
recordSchema.pre('validate', function (next) {
console.log(this);
this.extras = this.extras.map(v => v.value);
this.skills = this.skills.map(v => v.value);
return next();
});
When I log this in the pre-validate hook, I see that the values are missing:
{
extras: [],
skills: []
}
How can I ensure that the values are properly mapped from the objects to strings before saving the record?
Any key/val set that does not exist in your schema is always ignored.
The
[{value: 'string'}]does not match theextraskey in the schema, it will be ignored.Debug logs:
Compare the
r1document and ther2document. You can't transform/process the invalid keys/values inpre('validate')middleware because mongoose will ignore them. So, try to process thereq.bodyto match the keys/values in the schema and use the proceed data to create the model instance.