美文网首页
node MongoDB express

node MongoDB express

作者: 小学生的博客 | 来源:发表于2017-11-28 14:19 被阅读13次

    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')
        //插入数据
        // let data = [
        //     {"name": 'jan', age: 24, job: 'fontend'}
        // ]
        // collection.insert(data, (err, result) => {
        //     if (err) {
        //         return
        //     }
        //     callback(result)
        // })
    
        //查询数据
        let str={"name":'jan'}
        collection.find(str).toArray((err,result)=>{
            callback(result)
        })
        //更新数据
        let strB = {"name":'jan'}
        let strE = {$set:{"name":'CCC',age:25}}
        collection.update(strB,strE,(err,result)=>{
            callback(result)
        })
        //删除数据
        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
    

    如果出现

    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" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css")
                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
    

    相关文章

      网友评论

          本文标题:node MongoDB express

          本文链接:https://www.haomeiwen.com/subject/olosbxtx.html