I have two JSON objects, In each, there is a firstname field. I want to rename firstname to name, also want to import the existing firstname values to name, using mongoose.
Schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const user = new Schema({
firstname:{ type:String },
lastname:{ type:String },
username:{ type:String },
password:{ type:String },
user_type:{ type:String },
})
module.exports = mongoose.model('user', user)
Data Sample:
_id: "5bf5fbef16a06667027eecc2", firstname: "Hareesh", lastname: "Pitchikala", username: "123", password: "123", user_type: "employer", __v: 0
First, you'll need to add name
to your schema so it becomes:
const user = new Schema({
name: { type:String },
firstname: { type:String }, //keep this for now
lastname: { type:String },
username: { type:String },
password: { type:String },
user_type: { type:String },
});
Now, in your app code somewhere, you'll need to run this:
User.updateMany({}, { $rename: { firstname: 'name' } }, { multi: true }, function(err, blocks) {
if(err) { throw err; }
console.log('done!');
});
Now, you can remove firstname
from your schema if you wish.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With