Nodejs脚本实现从mongo数据库迁移数据至mysql数据库

时间:2022-05-25 08:22:49
weibo.js
var mongoose = require('mongoose');
var connection = mongoose.createConnection('mongodb://127.0.0.1:27017/weibodata');
var Schema = mongoose.Schema;
var weiboSchema = new Schema({
content : String,
uid : String
}, {
collection: 'micro_blog'
});

weiboSchema.methods.findList = function(callback) {
return this.model('micro_blog').find({"uid" : "1730096327"}, callback);
}

var WeiboModel = connection.model('micro_blog', weiboSchema);

var weiboEntity = new WeiboModel({});

module.exports = weiboEntity;

main.js

var weiboEntity     = require('./weibo.js');
var mysql = require('mysql');

var myslconnection = mysql.createConnection({
host : '127.0.0.1',//mysql服务器ip
user : 'root',//mysql登录名
password : 'root',//mysql登录密码
database : 'test'//mysql数据库名
});

myslconnection.query('set names utf8');

weiboEntity.findList(function(err, docs){
if (err) {
console.log('error');
} else {
for(var i=0;i<docs.length;i++) {
console.log("第" + (i + 1) + "条数据")
var content = docs[i].content;
var uid = docs[i].uid;
var sql = "insert into weibo (content, author) values('" + content + "','" + uid + "');";
myslconnection.query(sql, function(err, rows) {
if(err){
console.log(err);
}
});
}
console.log("ok")
}
})