Ali Mousavi
Ali Mousavi

Reputation: 38

Mogoose: Check if fields exist in schema before updating a document

I have a collection model like this:

const Task = mongoose.model('Task', {
  description: {
    type: String,
    trim: true,
    required: true
  },
  completed: {
    type: Boolean,
    default: false
  }
})

Currently, When a user tries to update a document using the API, any field that is not in the schema will be ignored, and the document will be updated. I want to throw an error if the user sends an update request to the API with a field that is not available in the database.

if I have a task with id of 12345 in the database:

{
  _id: 12345,
  description: "Buy cheese."
  completed: false
}

and a user sends an update query to the API for a the task:

id = '12345'
updates = {
  description: 'Buy Milk',
  due: '1 Week' //<-- Invalid Field
}

And I use this object to update the document:

await Task.findByIdAndUpdate(id, updates)

mongoose completely ignores the invalid due field and updates the document with the new description field.

Is there a clean way to avoid this sort of invalid update requests?

Upvotes: 1

Views: 1795

Answers (2)

Zaid abu khalaf
Zaid abu khalaf

Reputation: 1054

There is a way i found which is:

const params = Object.keys(req.body) // req.body is the updates coming from API
const allowedMethods = ["completed", "description"];
const isValidOperation = params.every((param) => allowedMethods.includes(param));

if (!isValidOperation) {
   return res.status(400).send({ error: "invalid update" });
}

Upvotes: 1

sushant mehta
sushant mehta

Reputation: 1284

While updating add in criteria the key that comes from the front end with $exists if it's not found in database update will not return any data and you can throw an error in that case.

criteria will be {_id:id};
update will be {description: 'Buy Milk'};
if(payload.due){
   criteria.due:{$exists:true},
   update.due=payload.due
}

let updatedData= await Task.update(criteria,update) if(updatedData.n== 0) throw error invalid parameters passed

// https://docs.mongodb.com/manual/reference/method/db.collection.update/ and this only use one query

Upvotes: 0

Related Questions