1.創建工程
E:\test>express mongo -e
create : mongo
create : mongo/package.json
create : mongo/app.js
create : mongo/public
create : mongo/public/javascripts
create : mongo/views
create : mongo/views/index.ejs
create : mongo/views/error.ejs
create : mongo/routes
create : mongo/routes/index.js
create : mongo/routes/users.js
create : mongo/public/images
create : mongo/public/stylesheets
create : mongo/public/stylesheets/style.css
create : mongo/bin
create : mongo/bin/www
install dependencies:
> cd mongo && npm install
run the app:
> SET DEBUG=mongo:* & npm start
E:\test>
2.安裝MongoDB模塊
E:\test>cd mongo
E:\test\mongo>npm install mongodb -save
[email protected] node_modules\mongodb
├── [email protected]
├── [email protected] ([email protected], [email protected], inherits@2
.0.1, [email protected])
└── [email protected] ([email protected], [email protected])
E:\test\mongo>
npm install 與 npm install -save的區別是:後者安裝的同時,將信息寫入package.json中項目路徑中,如果有package.json文件時,直接使用npm install方法就可以根據dependencies配置安裝所有的依賴包,這樣代碼提交到github時,就不用提交node_modules這個文件夾了。
3.連接MongoDB數據庫
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
加上監聽讓我們能通過入口啓動(也就是輸入 node app 不需要輸入 npm start了)app.listen(3000, function () {
console.log('app is listening at port 3000');
});
聲明MongoClientvar MongoClient = require('mongodb').MongoClient;
連接mongodb (其中localhost是地址後面跟的是端口以及數據庫名字,請根據自己情況修改)var url = 'mongodb://localhost:27017/first';
MongoClient.connect(url, function(err, db) {
console.log("數據庫連接成功");
db.close();
});
啓動服務(我們現在輸入node app啓動)E:\test\mongo>node app
module.js:340
throw err;
^
Error: Cannot find module 'express'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:289:25)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at Object.<anonymous> (E:\test\mongo\app.js:1:77)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:313:12)
at Function.Module.runMain (module.js:467:10)
好吧,報錯了 原來是我們忘記安裝依賴模塊了E:\test\mongo>npm install
[email protected] node_modules\ejs
[email protected] node_modules\debug
└── [email protected]
[email protected] node_modules\serve-favicon
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]
[email protected] node_modules\cookie-parser
├── [email protected]
└── [email protected]
[email protected] node_modules\morgan
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected] ([email protected])
[email protected] node_modules\express
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected] ([email protected])
├── [email protected] ([email protected])
├── [email protected] ([email protected], [email protected])
├── [email protected] ([email protected], [email protected], [email protected], [email protected], http
[email protected])
├── [email protected] ([email protected], [email protected])
└── [email protected] ([email protected], [email protected])
[email protected] node_modules\body-parser
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected] ([email protected])
├── [email protected] ([email protected], [email protected])
├── [email protected] ([email protected], [email protected], [email protected])
└── [email protected] ([email protected], [email protected])
E:\test\mongo>
再來,搞定了^-^E:\test\mongo>node app
app is listening at port 3000
數據庫連接成功
4.對數據庫進行操作
插入數據到數據庫:
var insertDocument = function(db, callback) {
//連接表
var collection =db.collection('first');
var user={
name:'Dandy',
age:18
}
//插入數據
collection.insertOne( user, function(err, result) {
if(err){
console.log(err)
}
console.log("插入成功");
callback();
});
};
修改數據庫連接代碼MongoClient.connect(url, function(err, db) {
console.log("數據庫連接成功");
insertDocument(db,function(){
db.close();
})
});
插入成功E:\test\mongo>node app
app is listening at port 3000
數據庫連接成功
插入成功
查詢數據庫中數據:
var findRestaurants = function(db, callback) {
var cursor =db.collection('first').find( );
cursor.each(function(err, result) {
if (result != null) {
console.log(result);
} else {
callback();
}
});
};
修改數據庫連接代碼MongoClient.connect(url, function(err, db) {
console.log("數據庫連接成功");
findRestaurants(db, function() {
db.close();
});
});
查詢成功(ctrl+c可以關閉node服務)E:\test\mongo>node app
app is listening at port 3000
數據庫連接成功
插入成功
^C
E:\test\mongo>node app
app is listening at port 3000
數據庫連接成功
{ _id: 56fc8e6d58257d7101dfafa0, name: 'tom', age: 13 }
{ _id: 56fc907858257d7101dfafa2, name: 'tom2', age: 2 }
{ _id: 56fc907858257d7101dfafa3, name: 'tom3', age: 3 }
{ _id: 56fc907858257d7101dfafa4, name: 'tom4', age: 4 }
{ _id: 56fc907858257d7101dfafa5, name: 'tom5', age: 5 }
{ _id: 56fc907858257d7101dfafa6, name: 'tom6', age: 6 }
{ _id: 56fc907858257d7101dfafa7, name: 'tom7', age: 7 }
{ _id: 56fc907858257d7101dfafa8, name: 'tom8', age: 8 }
{ _id: 56fc907858257d7101dfafa9, name: 'tom9', age: 9 }
{ _id: 56fccb1c8865f98415ed939f, name: 'Dandy', age: 18 }
var findRestaurants = function(db, callback) {
var cursor =db.collection('first').find({name:'Dandy'} );
cursor.each(function(err, result) {
if (result != null) {
console.log(result);
} else {
callback();
}
});
};
查詢成功E:\test\mongo>node app
app is listening at port 3000
數據庫連接成功
{ _id: 56fccb1c8865f98415ed939f, name: 'Dandy', age: 18 }
or查詢:
var findRestaurants = function(db, callback) {
var cursor =db.collection('first').find({$or :[{name:'Dandy'},{age:3}]});
cursor.each(function(err, result) {
if (result != null) {
console.log(result);
} else {
callback();
}
});
};
查詢成功E:\test\mongo>node app
app is listening at port 3000
數據庫連接成功
{ _id: 56fc907858257d7101dfafa3, name: 'tom3', age: 3 }
{ _id: 56fccb1c8865f98415ed939f, name: 'Dandy', age: 18 }
修改數據庫中數據
增加如下代碼var updateRestaurants = function(db, callback) {
var collection =db.collection('first');
collection.updateOne({name:"Dandy"},{$set: {age:13}}, function(err, results) {
console.log(results.result);
callback();
});
};
修改數據庫連接代碼MongoClient.connect(url, function(err, db) {
console.log("數據庫連接成功");
updateRestaurants(db, function() {
findRestaurants(db,function(){
db.close();
})
});
});
E:\test\mongo>node app
app is listening at port 3000
數據庫連接成功
{ ok: 1, nModified: 0, n: 1 }
{ _id: 56fc907858257d7101dfafa3, name: 'tom3', age: 3 }
{ _id: 56fccb1c8865f98415ed939f, name: 'Dandy', age: 13 }
刪除數據庫中數據
var removeRestaurants = function(db, callback) {
var collection =db.collection('first');
collection.deleteMany(
{ name: "tom2" },
function(err, results) {
console.log(results.result);
callback();
}
);
};
修改findRestaurants代碼(改爲查詢所有)var findRestaurants = function(db, callback) {
var cursor =db.collection('first').find();
cursor.each(function(err, result) {
if (result != null) {
console.log(result);
} else {
callback();
}
});
};
修改數據庫連接代碼MongoClient.connect(url, function(err, db) {
console.log("數據庫連接成功");
removeRestaurants(db, function() {
findRestaurants(db,function(){
db.close();
})
});
});
E:\test\mongo>node app
app is listening at port 3000
數據庫連接成功
{ ok: 1, n: 0 }
{ _id: 56fc8e6d58257d7101dfafa0, name: 'tom', age: 13 }
{ _id: 56fc907858257d7101dfafa3, name: 'tom3', age: 3 }
{ _id: 56fc907858257d7101dfafa4, name: 'tom4', age: 4 }
{ _id: 56fc907858257d7101dfafa5, name: 'tom5', age: 5 }
{ _id: 56fc907858257d7101dfafa6, name: 'tom6', age: 6 }
{ _id: 56fc907858257d7101dfafa7, name: 'tom7', age: 7 }
{ _id: 56fc907858257d7101dfafa8, name: 'tom8', age: 8 }
{ _id: 56fc907858257d7101dfafa9, name: 'tom9', age: 9 }
{ _id: 56fccb1c8865f98415ed939f, name: 'Dandy', age: 13 }