首先引入连接mogodb的模块,开始连接数据库
var mongodb = require('mongodb'); //引入模块
var server = new mongodb.Server('localhost', 27017, {auto_reconnect: true}); //连接数据库
var db = new mongodb.Db('mydb', server, {safe: true});//进入库
增加信息代码
db.open(function(err, db) {
if(!err) {
db.collection('mycoll', {
safe: true
}, function(err, collection) {
collection.insert({id: 1}, {safe: true}, function(err, result) {
console.log(result);
});
} else {
console.log(err);
}
});
});
删除信息
db.open(function(err, db) {
if(!err) {
db.collection('mycoll', {
safe: true
}, function(err, collection) {
collection.remove({id: 1}, {safe: true}, function(err, result) {
console.log(result);
});
} else {
console.log(err);
}
});
});
db.open(function(err, db) {
if(!err) {
db.collection('mycoll', {
safe: true
}, function(err, collection) {
collection.update({id: 1}, {$set: {name: "lily"}}, {safe: true}, function(err, result) {
console.log(result);
});
} else {
console.log(err);
}
});
});
db.open(function(err, db) {
if(!err) {
db.collection('mycoll', {
safe: true
}, function(err, collection) {
collection.find({id: 1}).toArray(function(err,val){
console.log(val);
});
} else {
console.log(err);
}
});
});
db.open(function(err, db) {
if(!err) {
db.dropCollection('mycoll',{safe:true},function(err,result){
if(err){
console.log('删除失败:');
console.log(err);
}else{
console.log('删除成功:');
console.log(result);
}
});
});