Reputation:
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.
Upvotes: 5
Views: 3094
Reputation: 81
This is now a breaking change in v4.13.19. ( atleast onwards v4.13.19)
You can now only -
https://github.com/Automattic/mongoose/issues/4801
Upvotes: 3
Reputation: 531
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();
Upvotes: 1
Reputation: 39186
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
}
Upvotes: 2