zlaayaa
zlaayaa

Reputation: 615

MongoDB migrations for .NET Core

I have a .NET Core project that works with mongoDb. I did the research about data migrations and neither one solution works for me.

There is MongoMigrations NuGet package but it is not compatible with .NET Core. A goal is to have some method that will check current db version and if it is not up to date, to do the certain update, for example to call some RemoveUserCollection() method or something like that.

Did anyone have the same problem, or even better a solution for that? :)

Thanks!

Upvotes: 2

Views: 4438

Answers (1)

Kevin Smith
Kevin Smith

Reputation: 14436

I've stumbled on this issue a few times myself but it takes pretty much 2mins to just manually bake it into your application startup or just script it out using javascript and deploy it like any other system change.

I've got a PowerShell script like

param([Parameter(Mandatory=$True)][string]$Hostname, [string]$Username = $null, [string]$Password = $null)

if($Username){
    $authParameters = "-u $Username -p $Password --authenticationDatabase admin"
}

Write-Host "Running all migration scripts..."
$scripts = Get-Childitem | where {$_.extension -like '.js'} | foreach { $_.Name }
Invoke-Expression "c:\mongodb\bin\mongo.exe --host $Hostname $authParameters $scripts"

then I just dump a load of .js files in the same directory.

;
(function () {
    var migration = { _id: ObjectId("568b9e75e1e6530a2f4d8884"), name: "Somekinda Migration (929394)" };

    var testDb = db.getMongo().getDB('test');
    if (!testDb.migrations.count({ _id: migration._id })) {
        testDb.migrations.insert(migration);
        print('running ' + migration.name)

        // Do Work
        testDb.people.find().snapshot().forEach(
            function (alm) {
                testDb.people.save(
                    {
                        modifiedAt: new Date(),
                    });
            }
        )
    }
})();

Upvotes: 2

Related Questions