How to move all document from one database to another using Mongoose

I had two databases with the same schema, one was for frequent query use, and one was for backup storage.

Database A:

[{
apple: 3,
name: "Peter"
},
{
apple: 6,
name: "admin"
},
]

Database B:

[{
apple: 43,
name: "kelly"
}
]

After running the moving command, I wish to move all documents from database A to database B for backup and clean up some space in database A.
Result:
Database A:

[]

Database B:

[{
apple: 3,
name: "Peter"
},
{
apple: 6,
name: "admin"
},
{
apple: 43,
name: "kelly"
}
]

How could I achieve it using Mongoose? Thank you.

Hey @WONG_TUNG_TUNG,

I’ve written a small JS script to move the document from one collection to another collection in the same database:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/testdb');

const SchemaA = new mongoose.Schema({
    name: String,
    apple: Number
});

const ModelA = mongoose.model('ModelA', SchemaA);

const SchemaB = new mongoose.Schema({
    name: String,
    apple: Number
});

const ModelB = mongoose.model('ModelB', SchemaB);

// function to move docs
async function moveDocuments() {

    // get docs from ModelA
    const docs = await ModelA.find().lean();

    // insert into ModelB
    await ModelB.create(docs);

    // delete from ModelA
    await ModelA.deleteMany({});
    console.log('Documents moved!');

}

// call function
moveDocuments();

Please note that the code has been provided based on the sample data and the requirements mentioned above. The recommendation would be to perform thorough testing before using it in the production environment.

Regards,
Kushagra

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.