DEV Community

Sulaiman Aminu Barkindo
Sulaiman Aminu Barkindo

Posted on

How to Rename a Field in Mongoose with Example

Introduction
Sometimes you may want to change the name of a field in your Schema for different reasons. If you are using mongoose performing only $rename operation may not work for you. In this article, you will see how to achieve renaming a field in mongoose in three (3) easy steps.

Let's Dive In
Assuming we have this user schema
{
firstName: String,
surname: String,
username: String
}

and we have documents in the collection
[
{
"_id": ObjectId("5a934e000102030405000000"),
"firstName": "Sulaiman",
"surname": "Aminu",
"username": "souley"
},
{
"_id": ObjectId("5a934e000102030405000001"),
"firstName": "Alice",
"surname": "Bob",
"username": "Aladin"
}
]

we want to rename the field surname to lastName

Step 1: Add the New field Name in the Schema
To rename a field you need to first add the name you want the field to become in your schema.
{
firstName: String,
surname: String, // leave this for now
lastName: String, // this is the added field
username: String
}

Step 2: Rename the Field using $rename
we can use the following code to rename the field.
db.collection.updateMany({}, { $rename: { "surname": "lastName" } } )

Now the documents will look like this
[
{
"LastName": "Aminu",
"_id": ObjectId("5a934e000102030405000000"),
"firstName": "Sulaiman",
"username": "souley"
},
{
"_id": ObjectId("5a934e000102030405000001"),
"firstName": "Alice",
"lastName": "Bob",
"username": "Aladin"
}
]

Step 3: Remove the old Field Name if You Want to
Now, we can safely delete the old field name from our schema if we don't need it anymore.
{
firstName: String,
surname: String, // you can remove this now
lastName: String,
username: String
}

In Conclusion
To rename a field in mongoose you will need to add the new field in the schema, rename the field with $rename operator, and lastly, delete the field from your schema if you want to.

More Info on $rename

Top comments (0)