Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

126
Views
Does mongoose filter out extra properties?

I'm about to work on a new app. And we've decided to use mongo as our db for quick prototyping along with mongoose for an orm. My question is, after declaring a new model. When I try to save a new model will it filter out extra keys? For example. Let's say a model has one property name. Will the model ignore extra keys?

let user = new User({
  name:"bob",
  randomKey: ""
}); 

user.save();

The reason is because I want to be able to do this in an express controller.

let user = new User({ ...req.body});
user.save();

Or in cases where a schema has many props.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Yes, mongoose doesn't save the fields that are not present on the schema definition.

Student schema:-

var Student = mongoose.model('Student', { name: String, event : String });

Post request:-

{
    "name" : "extra fields",
    "event" : "from postman",
    "event2" : "not on schema"
}

Collection:-

The event2 attribute (not part of Student schema) has not been saved.

{
    "_id" : ObjectId("5901d1d830fa36f020e88ea7"),
    "name" : "extra fields",
    "event" : "from postman",
    "__v" : 0
}

Mongoose schema save issue

over 4 years ago · Santiago Trujillo Report

0

This is now a breaking change in v4.13.19. ( atleast onwards v4.13.19)

You can now only -

  1. Save fields described in schema ( strict : true)
  2. Or make strict : false, and allow anything to be saved.

https://github.com/Automattic/mongoose/issues/4801

over 4 years ago · Santiago Trujillo Report

0

Mongoose wont save any field which is not present int the schema, you need to define a schema like -

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var productSchema = new Schema({
    title: String,
    author: String
});

module.exports = mongoose.model('Product', productSchema);

saving product

var newProduct = new Product();

// set the user's local credentials
newProduct.title  = title;
newProduct.author = author;
newProduct.addintionalData = 'RandomData'; //wont save this data

newProduct.save();
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!