11

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

Aditya Raval
  • 590
  • 4
  • 20
  • 1
    Isn't this just an update script to migrate ids ? Something like https://stackoverflow.com/questions/4973095/mongodb-how-to-change-the-type-of-a-field – s7vr Oct 27 '17 at 07:32
  • How is it possible to change the type of a field which is the primary key in MongoDB! – Aditya Raval Oct 28 '17 at 12:33
  • 1
    You can iterate over collection;check id's type when string remove the doc's id and insert the doc. After you are done inserting new documents you can bulk remove all the documents where id's type is string to remove old records. ex here https://stackoverflow.com/questions/4012855/how-update-the-id-of-one-mongodb-document – s7vr Oct 28 '17 at 13:59

1 Answers1

1

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" }});