nodejs和mongodb实践

时间:2023-03-09 16:53:16
nodejs和mongodb实践

首先,当然是都安装了nodejs 和mongodb了。这必须是前提条件。

现在我们要用nodejs连接mongodb数据库了。我这里只是一个非常非常简单是实践,初学嘛。更深入的学习之后,我会仔细写笔记记录的。自己走过的弯路,遇到的问题,肯定有价值的。好了,不多说了,开始动手吧。

我是在D盘nodework目录下创建了一个mytest文件夹的,然后在里面创建一个test.js。接着用npm安装mongodb,在cmd窗口找到新建的文件夹目录,命令

npm install mongodb

这样只会在mytest目录里安装相关的,一会儿我们可以看到多了node_modules文件夹,里面包含了各种依赖文件。如下图

nodejs和mongodb实践

接下来打开test.js文件,在里面写相关代码,我偷懒了,复制了别人代码,只是改了连接的数据库。创建数据和表格可以看我上篇笔记。这里不多说了。代码。

var  mongodb = require('mongodb');
var server = new mongodb.Server('localhost', 27017, {auto_reconnect:true});
var db = new mongodb.Db('blog', server, {safe:true});//blog是数据库 //连接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种连接方式mycoll是表格当然是我这么说的,在mongodb里是文档
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);
}
});

然后在cmd窗体里输入node test.js命令

出现结果如下:

nodejs和mongodb实践

就这样用nodejs连接mongodb数据库了。