var mongodb = require('mongodb');
var server = new mongodb.Server('localhost', 27017, {auto_reconnect:true});
var db = new mongodb.Db('mydb', server, {safe:true});
//连接db
db.open(function(err, db){
if(!err){
console.log('connect db');
db.createCollection('first', {safe:true}, function(err, collection){
if(err){
console.log(err);
}else{
console.log('ok');
//新增数据
var person01={"学号":"2011012301","name":"张三","email":"zhangs001@nenu.edu.cn","teacher":"呵呵01"};
var person02={"学号":"2011012302","name":"李四","email":"lis002@nenu.edu.cn","teacher":"呵呵02"};
var person03={"学号":"2011012303","name":"王五","email":"wangw003@nenu.edu.cn","teacher":"呵呵01"};
collection.insert(person01);
collection.insert(person02);
collection.insert(person03);
console.log("isnert success");
//查找
collection.find(function (err, cursor) {
cursor.each(function (err, doc) {
if (doc) {
console.log('doc.学号:' + doc.学号,'doc.name:' + doc.name,'doc.email:' + doc.email,'doc.teacher:' + doc.teacher);
}
});
});
}
});
//删除
console.log('delete first');
db.dropCollection('first');
}else{
console.log(err);
}
});
nodejs直接操作mongodb
最新推荐文章于 2024-10-31 14:22:03 发布