Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

127
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda