node鏈接mongodb數(shù)據(jù)庫的方法詳解【阿里云服務(wù)器環(huán)境ubuntu】
本文實(shí)例講述了node鏈接mongodb數(shù)據(jù)庫的方法。分享給大家供大家參考,具體如下:
一、安裝2.6版本以上的mongodb在云服務(wù)器上(百度就能查到安裝方法,以及驗(yàn)證是否安裝成功一般是mongodb –version);
二、因?yàn)閙ongodb的默認(rèn)開啟端口是27017,所以要在Ubuntu上開啟這個(gè)端口:
ufw allow 27017
ufw enable
ufw reload
ufw status //這是查看這個(gè)端口是否開啟,iptables --list也可以查看
光在服務(wù)器開了端口還不行,還要在阿里云服務(wù)器控制臺(tái)的安全組中添加這個(gè)端口:

三、在node項(xiàng)目中利用npm安裝mongodb:
npm i mongodb --save
四、鏈接的具體代碼(前提是已經(jīng)建立了簡單的http或者h(yuǎn)ttps服務(wù)),具體代碼:
const http = require('http')
, https = require('https');
const express = require('express');
const bodyParser = require('body-parser')
const app = express();
const fs = require('fs');
const ejs = require('ejs');
const path = require('path');
const MongoClient = require('mongodb').MongoClient;
// 返回信息
const questions = {
code: 200,
msg: 'success',
};
// https證書,開https服務(wù)的自驗(yàn)證證書
const options = {
key: fs.readFileSync('./privatekey.pem'),
cert: fs.readFileSync('./certificate.pem')
};
let xltitle = '標(biāo)題(初始化數(shù)據(jù))',
xlcontent = '內(nèi)容(初始化數(shù)據(jù))',
xlfaceid = '1(初始化數(shù)據(jù))';
const url = 'mongodb://127.0.0.1/xlbase';
// 默認(rèn)端口27017,無需填寫
// 也可以修改端口,vim /etc/mongodb.conf
// 初始化數(shù)據(jù)庫
MongoClient.connect(url, function (err, db) {
if (err) throw err;
let database = db.db('xlbase');
console.log('------------數(shù)據(jù)庫初始化成功------------');
// 如果沒有face這個(gè)集合,會(huì)創(chuàng)建一個(gè),所以可以用這個(gè)來初始化集合
database.createCollection('face', function (err, res) {
if (err) throw err;
console.log('------------集合初始化完畢------------');
db.close();
});
});
//設(shè)置跨域訪問
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1');
// res.header("Content-Type", "application/json;charset=utf-8");
next();
});
// parse application/x-www-form-urlencoded 解析
app.use(bodyParser.urlencoded({extended: false}));
// parse application/json 解析
app.use(bodyParser.json());
// view engine setup,視圖模版
app.set('views', path.join(__dirname, './'));
app.set('view engine', 'jade');
// 靜態(tài)資源解析路徑(css,js,圖片等)
app.use(express.static(path.join(__dirname, './static')));
// 數(shù)據(jù)接收接口
app.post('/info', function (req, res) {
res.header("Content-Type", "application/json;charset=utf-8");
res.status(200);
xltitle = req.body.title;
xlcontent = req.body.content;
xlfaceid = req.body.faceId;
let info = {
'faceid': xlfaceid,
'title': xltitle,
'content': xlcontent
};
let faceid = {
'faceid': xlfaceid
};
let updateInfo = {$set: info};// 組裝更新的信息
MongoClient.connect(url, function (err, db) {
let database = db.db('xlbase');
database.collection('face').find(faceid).toArray(function (err, result) {
if (err) throw err;
// 判斷集合中faceid和當(dāng)前傳過來的faceid是否相同和存在
// 如果不存在就新插入這條數(shù)據(jù)
// 如果存在且相同,就更新數(shù)據(jù)
if (result.length !== 0 && result[0].faceid === xlfaceid) {
database.collection("face").updateOne(faceid, updateInfo, function (err, res) {
if (err) throw err;
console.log("------------數(shù)據(jù)更新成功------------");
db.close();
});
} else {
database.collection('face').insertOne(info, function (err, res) {
if (err) throw err;
console.log("------------數(shù)據(jù)添加成功------------");
db.close();
})
}
})
});
res.json(questions); // 返回信息
res.end(JSON.stringify(req.body, null, 2))
});
app.get('/index', function (req, res) {
res.status(200);
res.header("Content-Type", "text/html;charset=utf-8");
// 根據(jù)faceId查詢數(shù)據(jù)
MongoClient.connect(url, function (err, db) {
if (err) throw err;
let dbo = db.db("xlbase");
let face = {"faceid": xlfaceid}; // 查詢條件
let xltitle1 = 404;
let xlcontent1 = '網(wǎng)頁出錯(cuò)!';
dbo.collection("face").find(face).toArray(function (err, result) {
if (err) throw err;
console.log(result);
xltitle1 = result[0].title;
xlcontent1 = result[0].content;
db.close();
console.log('------------查詢完畢------------');
res.send('<h3 style="font-size: 35px">' + xltitle1 + '</h3>' +
'<pre style="white-space: pre-wrap;word-wrap: break-word;font-size: 30px">' + xlcontent1 + '</pre>');
res.end();
});
});
})
// 配置服務(wù)端口
// http.createServer(app).listen(3001, function () {
// console.log('3001')
// });
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; // 繞過證書驗(yàn)證
https.createServer(options, app).listen(8009, function () {
console.log('port: 8009');
});
// var server = app.listen(3001, function () {
//
// var host = server.address().address;
//
// var port = server.address().port;
//
// console.log('Example app listening at http://%s:%s', host, port);
// })
希望本文所述對(duì)大家nodejs程序設(shè)計(jì)有所幫助。
相關(guān)文章
Node.js connect ECONNREFUSED錯(cuò)誤解決辦法
這篇文章主要介紹了Node.js connect ECONNREFUSED錯(cuò)誤解決辦法的相關(guān)資料,需要的朋友可以參考下2016-09-09
詳解nodejs 開發(fā)企業(yè)微信第三方應(yīng)用入門教程
這篇文章主要介紹了詳解nodejs 開發(fā)企業(yè)微信第三方應(yīng)用入門教程,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-03-03
Node.js實(shí)現(xiàn)用戶評(píng)論社區(qū)功能(體驗(yàn)前后端開發(fā)的樂趣)
這篇文章主要介紹了Node.js實(shí)現(xiàn)用戶評(píng)論社區(qū)(體驗(yàn)前后端開發(fā)的樂趣) ,需要的朋友可以參考下2019-05-05
windows 下安裝nodejs 環(huán)境變量設(shè)置
windows 下安裝nodejs 了,也安裝了npm, 但是有時(shí)候切不能直接用request(‘ws’)這一類的東西.我覺得是確實(shí)環(huán)境變量或其他設(shè)置有問題,能否給個(gè)完整的設(shè)置方案:2017-02-02
Node.JS循環(huán)刪除非空文件夾及子目錄下的所有文件
這篇文章主要介紹了Node.JS循環(huán)刪除非空文件夾及子目錄下的所有文件及node.js遞歸刪除非空文件夾的實(shí)例代碼,需要的朋友可以參考下2018-03-03

