h1,h2,h3,h4,h5,h6,p,blockquote { margin: 0; padding: 0;}body { font-family: "Helvetica Neue", Helvetica, "Hiragino Sans GB", Arial, sans-serif; font-size: 13px; line-height: 18px; color: #737373; margin: 10px 13px 10px 13px;}a { color: #0069d6;}a:hover { color: #0050a3; text-decoration: none;}a img { border: none;}p { margin-bottom: 9px;}h1,h2,h3,h4,h5,h6 { color: #404040; line-height: 36px;}h1 { margin-bottom: 18px; font-size: 30px;}h2 { font-size: 24px;}h3 { font-size: 18px;}h4 { font-size: 16px;}h5 { font-size: 14px;}h6 { font-size: 13px;}hr { margin: 0 0 19px; border: 0; border-bottom: 1px solid #ccc;}blockquote { padding: 13px 13px 21px 15px; margin-bottom: 18px; font-family:georgia,serif; font-style: italic;}blockquote:before { content:"C"; font-size:40px; margin-left:-10px; font-family:georgia,serif; color:#eee;}blockquote p { font-size: 14px; font-weight: 300; line-height: 18px; margin-bottom: 0; font-style: italic;}code, pre { font-family: Monaco, Andale Mono, Courier New, monospace;}code { background-color: #fee9cc; color: rgba(0, 0, 0, 0.75); padding: 1px 3px; font-size: 12px; -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px;}pre { display: block; padding: 14px; margin: 0 0 18px; line-height: 16px; font-size: 11px; border: 1px solid #d9d9d9; white-space: pre-wrap; word-wrap: break-word;}pre code { background-color: #fff; color:#737373; font-size: 11px; padding: 0;}@media screen and (min-width: 1500px) { body { width: 1500px; margin:10px auto; }}
在node-mongodb-native 最新的API中推荐的链接数据库的方式改变啦。
让我们先看看以前版本中是怎么样连接数据库的方式。
服务器server连接方式
var mongodb = require('mongodb');
var server = new mongodb.Server('localhost', 27017, {auto_reconnect:true});
var db = new mongodb.Db('test', server, {safe:true});
db.open(function(err,db){
if(!err){
db.collection('mycoll',{safe:true}, function(err, connection){
var tmp={"name":"yk","age":20};
connection.insert(tmp,{safe:true},function(err,result){
console.log(result);
})
});
}else{
console.log(err);
}
});
还可以使用MongoClient
这个class来连接
MongoClient = function(server, options);
MongoClient.prototype.open
MongoClient.prototype.close
MongoClient.prototype.db
MongoClient.connect
这里我们看到open,close,db,connect的方法都在它的原型中。
客户端MongoClient连接方式
var mongodb=require('mongodb')
Db=mongodb.Db,
MongoClient=mongodb.MongoClient,
Server=mongodb.Server;
var mongoClient=new MongoClient(new Server("localhost",27017),{native_parse:true});
mongoClient.open(function(err,mongoclient){
var db=mongoclient.db("test");
db.collection('user',{safe:true}, function(err, connection){
var tmp={"name":"yk","age":20};
connection.insert(tmp,{safe:true},function(err,result){
console.log(result);
})
db.close();
});
})