nodejs连接mongodb的方法

时间:2021-05-27 17:55:22

一、

var express = require('express');
var mongodb = require('mongodb'); var app = express(); app.use(express.static('./website')); var url = 'mongodb://localhost:10089/test'; mongodb.MongoClient.connect(url, function (err, db) {
if (err) {
console.log(err); return false;
} console.log(db);
}); app.listen(9000); console.log('running');

二、

1、定义mongodb的连接串:

test_163:/home/exenode/part3/scms/config # more env/development.js
module.exports = {
port:7101,
mongodb:'mongodb://localhost:10089/scms'
}

 2、导出此连接串的配置:

test_163:/home/exenode/part3/scms/config # more config.js
var config = null; if (process && process.env && process.env.NODE_ENV){
config = require("./env/"+ process.env.NODE_ENV + ".js");
}else{
config = require("./env/development.js");
}; module.exports = config;

 3、使用mongoose.connect("连接串")  方法连接mongodb

test_163:/home/exenode/part3/scms/config # more mongoose.js
var mongoose = require('mongoose');
var config = require('./config'); module.exports = function(){
console.log("config:",config.mongodb);
var db= mongoose.connect(config.mongodb);
require('../app/models/news.server.model');
return db;
}

4、在 app.js 中执行 mongoose.js 中导出的方法,连接mongodb: 

test_163:/home/exenode/part3/scms # more app.js
var express = require('./config/express');
var mongodb = require('./config/mongoose'); var db = mongodb();
var app = express(); module.exports = app;