Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename field in mongoose [duplicate]

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
like image 816
Hareesh Avatar asked Nov 23 '18 12:11

Hareesh


1 Answers

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.

like image 158
Alex Avatar answered Sep 18 '22 23:09

Alex