Node.js测试MongoDB连接及操作

step 1. 进入需要测试的express项目目录
bogon:~ onefish$ ssh [email protected]
[email protected]'s password:
Last login: Wed Feb 22 16:29:56 2017 from 219.142.100.205

[email protected]:~
# cd /data/release/qcloud-applet-album/
[email protected]:/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. 进行测试
[email protected]:/data/release/qcloud-applet-album
# node models/order.js
{ title: 'forget',
  author: 'martwin',
  _id: 58ad4ddce324e90afce4d177 }
db is open
success
//测试成功,可根据功能进行详细开发

你可能感兴趣的:(Node.js测试MongoDB连接及操作)