使用node.js怎么对mongodb进行操作-创新互联
本篇文章为大家展示了使用node.js怎么对mongodb进行操作,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

首先安装nodejs mongodb
npm install mongodb
代码
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');
// 连接Collection(可以认为是mysql的table)
// 第1种连接方式
// db.collection('mycoll',{safe:true}, function(err, collection){
// if(err){
// console.log(err);
// }
// });
// 第2种连接方式
db.createCollection('mycoll', {safe:true}, function(err, collection){
if(err){
console.log(err);
}else{
//新增数据
// var tmp1 = {id:'1',title:'hello',number:1};
// collection.insert(tmp1,{safe:true},function(err, result){
// console.log(result);
// });
//更新数据
// collection.update({title:'hello'}, {$set:{number:3}}, {safe:true}, function(err, result){
// console.log(result);
// });
// 删除数据
// collection.remove({title:'hello'},{safe:true},function(err,result){
// console.log(result);
// });
// console.log(collection);
// 查询数据
var tmp1 = {title:'hello'};
var tmp2 = {title:'world'};
collection.insert([tmp1,tmp2],{safe:true},function(err,result){
console.log(result);
});
collection.find().toArray(function(err,docs){
console.log('find');
console.log(docs);
});
collection.findOne(function(err,doc){
console.log('findOne');
console.log(doc);
});
}
});
// console.log('delete ...');
// //删除Collection
// db.dropCollection('mycoll',{safe:true},function(err,result){
// if(err){
// console.log('err:');
// console.log(err);
// }else{
// console.log('ok:');
// console.log(result);
// }
// });
}else{
console.log(err);
}
});上述内容就是使用node.js怎么对mongodb进行操作,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注创新互联网站建设公司行业资讯频道。
另外有需要云服务器可以了解下创新互联建站www.cdcxhl.com,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
分享文章:使用node.js怎么对mongodb进行操作-创新互联
网站路径:http://www.jxjierui.cn/article/desdjd.html


咨询
建站咨询
