Reputation: 1286
I have already created one MongoDB collection using mongoose schema from express web service after some days I found a requirement of a new field in mongoose table so added that field in mongoose schema and try to insert a value of newly added field along with existing fields but it's not get inserted in the newly added document.
So what I have done as a troubleshooting process, I deleted my existing collection totally and then inserted my new document in a collection, Then I found It started working properly. My newly inserted field get inserted into the collection. So Is there any other way to add a new field in MongoDB using mongoose without deleting the whole collection.
My existing user collection schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
});
var User = mongoose.model('User', userSchema);
module.exports = User;
When I inserted a new document with username and password In above collection It works fine.
My new user collection schema after adding new field (name):
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
name: String,
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
});
var User = mongoose.model('User', userSchema);
module.exports = User;
But After updating my user schema When I inserted a new document with name, username and password In above collection only insert username and password, name field does not get inserted.
Upvotes: 2
Views: 1950
Reputation: 374
Just do one simple step, add default values to every field you create. Example
var userSchema = new Schema({
name: {type: String , default: ""},
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
});
Happy Coding
Upvotes: 2
Reputation: 124
Name should be also be an object in the schema like so
var userSchema = new Schema({
name: {type: String},
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
});
Upvotes: 0