美文网首页程序员
Node.js测试MongoDB连接及操作

Node.js测试MongoDB连接及操作

作者: 灵魂函数 | 来源:发表于2017-02-22 17:38 被阅读0次
    step 1. 进入需要测试的express项目目录
    bogon:~ onefish$ ssh root@119.29.53.119
    root@119.29.53.119's password:
    Last login: Wed Feb 22 16:29:56 2017 from 219.142.100.205
    
    root@10.104.79.160:~
    # cd /data/release/qcloud-applet-album/
    root@10.104.79.160:/data/release/qcloud-applet-album
    # node
    >
    >.exit
    
    step 2. 利用ForkLift and Sublime Text 创建 models/order.js
    /**
     * mongodb的order model
     */
    
    var mongoose = require("mongoose");
    mongoose.Promise = global.Promise; 
    mongoose.connect('mongodb://admin:admin@localhost/album'); //auth验证
    var db = mongoose.connection;
    db.on('error',console.error.bind(console,'connection error:'));
    db.once('open',function(callback){
        console.log('db is open');
    });
    var Schema = mongoose.Schema,
        ObjectId = Schema.ObjectId;
    
    var BlogPost = new Schema({
        author:String,
        title:String
    });
    
    var Blog = mongoose.model('Blog',BlogPost);
    /*
    var b = new Blog({
        author:'testblog',
        title:'test'
    });
    */
    var b = new Blog;
    b.author = 'martwin';
    b.title = 'forget';
    console.log(b);
    
    b.save(function (err) {
        // body...
        if(err){
            console.log(err)
        }
        console.log('success')
    })
    
    step 3. 进行测试
    root@10.104.79.160:/data/release/qcloud-applet-album
    # node models/order.js
    { title: 'forget',
      author: 'martwin',
      _id: 58ad4ddce324e90afce4d177 }
    db is open
    success
    //测试成功,可根据功能进行详细开发
    

    相关文章

      网友评论

        本文标题:Node.js测试MongoDB连接及操作

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