node.js將MongoDB數(shù)據(jù)同步到MySQL的步驟
前言
最近由于業(yè)務需要,APP端后臺需要將MongoDB中的數(shù)據(jù)同步到Java端后臺的MySQL中,然后又將MySQL中算好的數(shù)據(jù),同步到MongoDB數(shù)據(jù)庫。
這個過程看是很繁瑣,實際上這就是一個互相寫表的過程。
接下來就看看node.js將MongoDB中的數(shù)據(jù)批量插入到MySQL數(shù)據(jù)庫的實現(xiàn)過程。話不多說了,來一起看看詳細的介紹吧。
環(huán)境
- node.js
- MongoDB
- MySQL
- npm
需要的模塊
- mongoose
- MySQL
準備好MongoDB中的數(shù)據(jù)
- 比如說:我這里要同步的是用戶表,用戶表中包含username,email,password...
- 通過MongoDB shell命令插入1000條數(shù)據(jù)
實現(xiàn)
mongoose的Schema我這里就不寫了,大家可以上網(wǎng)進行查看,node.js連接MongoDB和MySQL的pool看下面:
node.js連接MongoDB:http://m.fzitv.net/article/98813.htm
Nodejs mysql pool使用實例:
mysql模塊為felixge/node-mysql
源碼如下:
/**
* Created by kevalin on 2015/4/22.
*/
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var conf = require('../config/dbconnection');
//定義pool池
var pool = mysql.createPool(
{
host : conf.dbMysql.host,
user : conf.dbMysql.user,
password : conf.dbMysql.password,
database : conf.dbMysql.database,
port : conf.dbMysql.port
}
);
router.get('/', function(req, res) {
var selectSites = "select *, date_format(do_time, '%Y-%m-%d %H:%i:%s') as time from siteinfo order by id";
pool.getConnection(function(err, connection) {
if (err) throw err;
connection.query(selectSites, function(err, rows) {
if (err) throw err;
res.render('sites', {title : '站點分布', results : rows});
//回收pool
connection.release();
});
});
});
module.exports = router;
下面上關鍵代碼
思路:
先從MongoDB查詢數(shù)據(jù)然后通過遍歷插入MySQL中。
User.find({}, (err, user) => {
if (err)
res.send(err);
for( let i = 0 ; i < family.length ; i ++ ) {
console.log("第" + (i + 1) + "條數(shù)據(jù)");
let username = user[i].username;
let email = user[i].email;
let password = user[i].password;
let sql = "insert into user_table(username, email, password) values ('" + username + "','" + email + "','" + password + "');";
pool.query(sql,(err, rows) => {
if (err)
res.send(err);
res.json({
message:'數(shù)據(jù)插入成功',
rows
});
});
}
});
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
- Python實現(xiàn)將數(shù)據(jù)框數(shù)據(jù)寫入mongodb及mysql數(shù)據(jù)庫的方法
- 記一次MongoDB性能問題(從MySQL遷移到MongoDB)
- Python中MySQL數(shù)據(jù)遷移到MongoDB腳本的方法
- MongoDB與MySQL的操作對比表及區(qū)別介紹
- MongoDB與MySQL常用操作語句對照
- MongoDB系列教程(五):mongo語法和mysql語法對比學習
- python連接MySQL、MongoDB、Redis、memcache等數(shù)據(jù)庫的方法
- mongodb與mysql命令詳細對比
- 基于MySQL到MongoDB簡易對照表的詳解
- MySQL和MongoDB設計實例對比分析
- 分析MongoDB和MySQL各自的關鍵特性、差別和優(yōu)勢
相關文章
nodejs實現(xiàn)連接mongodb數(shù)據(jù)庫的方法示例
這篇文章主要介紹了nodejs實現(xiàn)連接mongodb數(shù)據(jù)庫的方法,結合實例形式分析了nodejs針對mongodb數(shù)據(jù)庫的簡單連接、查詢及關閉等操作技巧,需要的朋友可以參考下2018-03-03
npm ERR! code ELIFECYCLE錯誤及解決方法
有時候在使用npm運行命令時,可能會遇到錯誤,本文主要介紹了npm ERR! code ELIFECYCLE錯誤及解決方法,具有一定的參考價值,感興趣的可以了解一下2024-05-05

