node.js 連接MongoDB
①安裝
cnpm install mongodb
②增刪改查
let MongoClient = require('mongodb').MongoClient
let url = 'mongodb://localhost:27017/test'
let insertData = (db, callback) => {
let collection = db.collection('site')
//插入數(shù)據(jù)
// let data = [
// {"name": 'jan', age: 24, job: 'fontend'}
// ]
// collection.insert(data, (err, result) => {
// if (err) {
// return
// }
// callback(result)
// })
//查詢數(shù)據(jù)
let str={"name":'jan'}
collection.find(str).toArray((err,result)=>{
callback(result)
})
//更新數(shù)據(jù)
let strB = {"name":'jan'}
let strE = {$set:{"name":'CCC',age:25}}
collection.update(strB,strE,(err,result)=>{
callback(result)
})
//刪除數(shù)據(jù)
let strD = {"name":'CCC'}
collection.remove(strD,(err,result)=>{
callback(result)
})
}
MongoClient.connect(url, (err, db) => {
insertData(db, (reslut) => {
console.log(reslut)
db.close()
})
})
mongoose 使用
cnpm install mongoose
如果出現(xiàn)
DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
mongoose.Promise = global.Promise; //連接前加上這句話
參考:https://www.cnblogs.com/zhongweiv/p/mongoose.html
項目中如何使用html模板
/* GET home page. */
router.get('/', function(req, res, next) {
// res.render('index', { title: 'Express' });
res.sendfile('./views/home.html')
});
jade中引入 bootstrap
doctype html
html
head
block scripts
link(rel="stylesheet" )
script(src="http://cdn.static.runoob.com/libs/jquery/2.1.1/jquery.min.js")
script(src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js")
body
h1 jade demo
button.btn.btn-primary.btn-lg learn more