Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Migration of Small Parse IDs to normal MongoDB's ObjectIDs

I am using Parse Dashboard for User Management of my iOS Application.Also, I am using external APIs which are using MongoDB database.

The issue currently I am facing is the User created from Parse Dashboard is having small id instead of MongoDB's ObjectID, and other resources which are not over parse are generated by normal ObjectID.

eg. User Object:

{
_id:"qVnyrGynJE",
user_name:"Aditya Raval"
}

Document Object:

{
_id:"507f191e810c19729de860ea",
doc_name:"Marksheet",
user:"qVnyrGynJE"
}

Task Object:

{
_id:"507f191e810c19729de860ea",
task_name:"Marksheet",
user:"qVnyrGynJE"
}

I am also using Keystone.js as a Backend Admin Dashboard.So basically due to this mix kind of IDs relationships inside KeyStone.js is broken and Keystone.js gets crashed.

So I want to migrate all my existing small IDs to normal MongoDB ObjectIDs without breaking into relationships or any other walkthrough by fixing Keystone.js

like image 767
Aditya Raval Avatar asked Oct 03 '17 09:10

Aditya Raval


1 Answers

You can run something like this:

var users = db.Users.find({});

for(var i = 0; i < users.length(); i++)
{
    var oldId = users[i]._id;
    delete users[i]._id;
    db.Users.insert(users[i], function(err, newUser) {
            db.Documents.updateMany({"user": oldId},{ $set: { "user": newUser._id }});
            //Do this for all collections that need to be update.
        });
    );
}

db.Users.deleteMany({_id: { $type: "string" }});
like image 174
Alex Petrescu Avatar answered Oct 13 '22 20:10

Alex Petrescu