I am trying to add markup
and sanitize my input but I keep getting an error;
This is my code;
const mongoose = require('mongoose');
const slug = require('slugify');
const createDomPurify = require('dompurify');
const marked = require('marked');
const {JSDOM} = require('jsdom');
const dompurify = createDomPurify( new JSDOM().window);
const CPASchema = {
//SOME PART OF THIS CODE BUT UNNECESSARY TO THE QUESTION
answer:{
type:String
},
sanitizedHTML:{
type: String,
required: true
}
}
CPASchema.pre('validate', async function(data, next){
if(data.answer) {
console.log('JUST BEFORE SANITIZING')
data.sanitizedHTML = await dompurify.sanitize(marked(data.answer));
}
next()
})
module.exports = mongoose.model('CPASchema', CPASchema);
This is the error I keep getting
CPASchema.pre('validate', async function(data, next){
^
TypeError: CPASchema.pre is not a function
EDIT
I have tried changing the mongoose
verion but that did not help
CodePudding user response:
You're calling the mongoose's methods before introducing your schema.
The part of your schema is nothing just a simple Javascript object, you need to pass it to the mongoose and use the returned object.
The below snippet might help you to understand the behavior.
const schema = new mongoose.Schema({ name: String });
schema.pre('save', () => console.log('Hello from pre save'));