DEV Community

loading...
Cover image for I made an easy-to-use MongoDB migration tool(sort of)

I made an easy-to-use MongoDB migration tool(sort of)

michaelgrigoryan25 profile image Michael Grigoryan ・2 min read

Hello everyone. For some time now I have seen some MongoDB migration tools for Node.js which didn't really offer a solution to my problem, they were rather overcomplicating it. So having that in mind I thought why not to create a mongodb model migration tool for Node.js. And so I started making mongutils

Getting started

It's actually very easy to get started. You just install the library like this

yarn add mongutils -D
# or with npm
npm i mongutils -D
Enter fullscreen mode Exit fullscreen mode

Using the library

Let's assume that we have a mongoose model like this one:

// Sample.model.js
module.exports = new mongoose.model("sample", {
  name: { type: String, required: true },
  age: { type: Number, required: true },
});
Enter fullscreen mode Exit fullscreen mode

Let's say that we have 1000+ documents using this schema and we want to add a surname property to all of those. Mongutils makes this very easy for us.

But first of all we'll need to update our model to look like this.

module.exports = new mongoose.model("sample", {
  name: { type: String, required: true },
  surname: { type: String, required: true },
  age: { type: Number, required: true },
});
Enter fullscreen mode Exit fullscreen mode

Then we'll create a simple script to add ONE field to all of those documents

const SampleSchema = require("./Sample.model");
const { toAll } = require("mongutils");

// Assuming that you're connected to mongoDB using mongoose

const UpdateModels = async () => {
    const { data } = toAll.addField(SampleSchema, "surname", /* Here can be an optional value (null by default) 
    */)
  console.log(data);
}

UpdateModels();
Enter fullscreen mode Exit fullscreen mode

That's it! With this little script you just added a field to all of the documents that didn't have the field you specified in them.

If you're interested you can read the Documentation

Thanks for reading this article.

Hope this helped you to save some time

If you have any suggestions, criticism about this project leave a comment and I'll respond.

Discussion (0)

pic
Editor guide