I am trying to implement PUT and PATCH request using Mongoose,the code for handing both requests are as follows:
function colCon(){
/* ... retrieve mongoose model ... */
}
function putData(_title = '', newData = {}){
console.log('> put data');
const condition = {title : _title};
return colCon().then(async model => {
return model.findOneAndReplace(
condition,
newData,
{
returnDocument : 'after',
strict : false
}
).then(doc => {
return doc;
}).catch(err => {
throw err;
})
}).catch(err => {
throw err;
})
}
function patchData(_title = '', newData = {}){
console.log('> patch data');
const condition = {title : _title};
return colCon().then(async model => {
return model.findOneAndUpdate(
condition,
newData,
{
returnDocument : 'after',
strict: false
}
).then(doc => {
return doc;
}).catch(err => {
throw err;
})
}).catch(err => {
throw err;
})
}
While both have similar approaches (retrieve model → find and update / replace → show after-modified result), the results are quite different. For example this is my intial schema and document
//schema
{
title: {
type: String,
unique: true,
required: true,
},
content: {
type: String,
}
}
//document sample
{
"content": "Something here",
"title": "Some title"
}
And this is the result after I update / replace with the same new data
//new data
{
"content": "Something new here",
"title": "Some title"
"car": "bugati"
}
//PATCH result
{
"content": "Something new here",
"title": "Some title",
"car": "bugati"
}
//PUT result
{
"content": "Something new here",
"title": "Some title"
}
Although I have turn off strict mode in both functions, extra fields is still prevented in PUT request.
How can I disable it in PUT function the same as PATCH?
Thank you in advance!