前言
最近由于業(yè)務(wù)需要,APP端后臺需要將MongoDB中的數(shù)據(jù)同步到Java端后臺的MySQL中,然后又將MySQL中算好的數(shù)據(jù),同步到MongoDB數(shù)據(jù)庫。
這個過程看是很繁瑣,實際上這就是一個互相寫表的過程。
接下來就看看node.js將MongoDB中的數(shù)據(jù)批量插入到MySQL數(shù)據(jù)庫的實現(xiàn)過程。話不多說了,來一起看看詳細(xì)的介紹吧。
環(huán)境
需要的模塊
準(zhǔn)備好MongoDB中的數(shù)據(jù)
實現(xiàn)
mongoose的Schema我這里就不寫了,大家可以上網(wǎng)進(jìn)行查看,node.js連接MongoDB和MySQL的pool看下面:
node.js連接MongoDB://m.survivalescaperooms.com/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});//回收poolconnection.release();});});});module.exports = router;下面上關(guān)鍵代碼
思路:
先從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 }); }); }});總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對錯新站長站的支持。
新聞熱點
疑難解答
圖片精選