coinhndp
coinhndp

Reputation: 2471

Security when passing req.body directly to mongo db

Does it consider security problem when I pass req.body directly to the database (I use mongoose and nodejs)?

Let's say I have a person schema (name: string, age: number) and in req.body, someone tries to add an extra field to it. Do I need to extract only field that I need before passing it to db

const {name, age} = req.body
const person = new Person({name, age})
person.save()...

OR this is ok because mongoose already take care of that

 const person = new Person(req.body)
    person.save()...

Note: I am asking about extra fields, not about whether or not we should santinize the field that declared in schema

Upvotes: 1

Views: 325

Answers (1)

TGrif
TGrif

Reputation: 5931

No, it's not a security problem in itself.
And that's not related with Mongoose either. That's pure JavaScript.

You are using destructuring assignment on the req.body params, so you are extracting exactly specified arguments.

const body = { name: 'bob', age: 12,  malicious_entry: "rm -rf" };

let {name, age} = body;
console.log(name, age, malicious_entry)  // ReferenceError: malicious_entry is not defined

And if you pass it to a constructor:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

let {name, age, malicious_entry} = body;
let person = new Person(name, age, malicious_entry);
console.log(person)  // Person { name: 'bob', age: 12 }

I let you choose if you want to record an internet request directly in your database without checking it, but clearly extra parameters are not the problem.

Upvotes: 1

Related Questions