10

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
Andrejs Cainikovs
  • 27,428
  • 2
  • 75
  • 95
Hareesh
  • 305
  • 1
  • 3
  • 12
  • 1
    This question is about Mongoose but it was flagged duplicate and link to MongoDB. Come on, it's not the same – Thinh NV Sep 16 '20 at 09:41

2 Answers2

24

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.

gazdagergo
  • 6,187
  • 1
  • 31
  • 45
Alex
  • 37,502
  • 51
  • 204
  • 332
  • 1
    Not sure but I have to add `strict:false` to the snippet to get it working: Also it said `DeprecationWarning: collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.` So I used `upadateMany` Fullcode: ``` User.updateMany( {}, { $rename: { firstname: 'name' } }, { multi: true, strict: false }, function (error) { if (error) { throw error; } console.log('done!'); } ); ``` – Thinh NV Sep 16 '20 at 09:35
  • 3
    `{ multi: true }`will be ignored. From docs: "...MongoDB will update all documents that match filter [...] regardless of the value of the multi option." – samura Jan 23 '22 at 23:01
0

Documents can be updated as below:

db.collection.updateMany({},{ $rename: { "firstname": "name" } } );
kRiZ
  • 785
  • 8
  • 14