mongodb 学习备注1

本文介绍了MongoDB的安装及配置方法,包括解决网络连接问题、配置远程访问、设置root用户和密码等,并演示了如何使用Node.js进行数据库操作。

按照网络教程安装好后,

输入mongo,进入命令状态。

会看到一些警告,具体参考https://blog.youkuaiyun.com/sunbocong/article/details/78106096

先略过,以npm中mongodb的example代码 在nodejs中测试连接,放服务器端不会出错。

出错:

null == 'MongoNetworkError: failed to connect to server [ip:27017] on first connect [MongoNetworkError: connect ETIMEDOUT 1

怀疑是网络配置错误,在代码上传到服务器端。ip换成127.0.0.1

或者在服务器端安装node

安装 Node.js

Wafer 的 Demo 需要 7.6 以上版本的 Node.js 才能运行,目前最新版本为 8.x,yum 本身不提供 Node.js 的源,所以首先我们得切换源:

curl --silent --location https://rpm.nodesource.com/setup_8.x | sudo bash -

接着就可以直接通过 yum 安装了:

yum -y install nodejs

同理,我们可以通过如下命令验证 Node.js 是否安装成功:

node -v

安装的版本是6.x,

卸载后,用

curl -sL https://rpm.nodesource.com/setup_8.x | bash -

得到8.11的版本,把setup_8.x改成setup_9.x也是8.11版本。。突然想起来,8.11比8.9大。。嘿嘿

现在还没有用到nginx,那么就nodejs,网站放哪里好呢?先放/usr/local/www/下吧。

下面要对mongodb做配置。

1.支持远程访问。在mongodb.conf里修改bindip,注释掉后仍旧无法远程访问。

具体看这篇文章,https://segmentfault.com/q/1010000002923686

可以通过

sudo netstat -nputl

查看外网服务是否已经开启,

如果已经开启,还要查看下防火墙是否开放27071端口

其实在ecs服务器上,只要在bindip里添加ecs服务器的内网ip就可以了,访问的时候用公网ip

2.如何设置root用户和密码,

出现[MongoNetworkError: connect ECONNREFUSE

3.如何创建数据库和管理这个数据库的用户。

2,3两个可以看https://blog.youkuaiyun.com/fofabu2/article/details/78983741,如果webserver和数据库在一台电脑上,还是bind 127.0.0.1 比较好,测试的时候打开就好了。何况可能需要对多个数据库中的数据进行查询分析。

4.mangodb多数据库查询

启动/停止/重启  sudo service mongod start/stop/restart

启动后才能用mongo shell登录

使用以下命令来查看mongodb的运行状态

service mongod status

出现错误

MongoNetworkError: connect ECONNREFUSED  应该是mongodb没有打开外网访问导致的。

mongodb的基本操作如下

// Connection URL
const url = 'mongodb://139.224.132.137:27017/xzt' ;
//const url = 'mongodb://127.0.0.1:27017';
// Database Name
const dbName = 'xzt' ;
// Use connect method to connect to the server
MongoClient . connect ( url , ( err , client ) => {

  assert . equal ( null , err );
// console.log(client);
  console . log ( "Connected successfully to server" );
const xzt = client . db ( 'xzt' );
  //const db = client.db(dbName);
xzt . createCollection ( 'assets' ,  ( err , res ) => {
  assert . equal ( null , err );
  console . log ( "创建集合!" );
  });

  let assets = xzt . collection ( 'assets' );
  assets . insertMany ( sheet1 ,( err , result ) => {
    assert . equal ( null , err );
    console . log ( "insertMany" );
  })
client . close ();


1.关键字段key,_id作为关键字段,如果没有指定_id,则创建_id字段。

2.默认字段,没有默认字段,因为一个集合的文档的字段名和字段数都不需要一样。

3.为每个文档新增一个字段,可以用update,新的字段和值。

4.如果要更新_id,可以用save方法?

5.用NoSQL来描述数据关系?

查询用find,如find.({name:"张三"})。返回的是Cursor,游标对象,如果希望转成json,

一个简单的查询,搞了一天,

collection. find({ "repo" : "salary"}). toArray();
返回的是Promise { <pending> }。

可以参考

浅析promise

https://www.cnblogs.com/renbo/p/8975234.html

promise是一个构造函数,也即是一个函数!

所以正确的写法是

collection. find({ "repo" : "salary"}). toArray(( err, res) =>{
ctx. body= res;
console. log( ctx. body);

});

那么,如何知道这个promise有几个参数呢? 比如这里的toArray里的callback是两个参数,如何知道呢?

ide有提示,也可以查官方的文档。

这个比较靠谱

http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#count

注意下面这个地址当前默认是3.6的写法。不过还是不太靠谱。建议参考上面的。

https://docs.mongodb.com/manual/reference/method/cursor.toArray/index.html

最后的问题,是如果要等待数据库操作,返回结果给客户端,要注意这是异步操作。需要在哪里加async/await呢?

如下这样写,不行?为什么不行,以后再分析吧。

router. post( '/api/queryLogs', async ( ctx, next) => {
ctx. body= "111";
//返回logs数据
// Connection URL
const url = 'mongodb://ip:27017/xzt';
//const url = 'mongodb://127.0.0.1:27017';

// Database Name
const dbName = 'xzt';
let form = ctx. request. body;
//console.log(ctx.request);
console. log( form. repo);
//return;
// Use connect method to connect to the server
await MongoClient. connect( url, async ( err, client) => {

ctx. body= "222";
assert. equal( null, err);
// console.log(client);
//console.log("Connected successfully to server");
const xzt = client. db( 'xzt');
//const db = client.db(dbName);
await xzt. createCollection( "logs", async ( err, collection) => {
assert. equal( null, err);
ctx. body= "333";
//console.log("创建集合!"+"logs");
await collection. find({ "repo" : "salary"}). toArray( async ( err, res) =>{
ctx. body= res;
console. log( ctx. body);

});

Async/Await用于mongodb driver

https://zhuanlan.zhihu.com/p/28158766

这个文字提出了一种方法。 不过觉得不好。既然用async/await了,就不要用then catch了。

其实很简单,有了async/await,如果要捕获错误,用try catch。

router. post( '/api/queryLogs', async ( ctx, next) => {
ctx. body= "111";
//返回logs数据
// Connection URL
const url = 'mongodb://ip:27017/xzt';
//const url = 'mongodb://127.0.0.1:27017';

// Database Name
const dbName = 'xzt';
let form = ctx. request. body;
//console.log(ctx.request);
console. log( form. repo);
//return;
// Use connect method to connect to the server
const client= await MongoClient. connect( url);
const xzt = client. db( 'xzt');
//const db = client.db(dbName);
const collection= await xzt. createCollection( "logs");
ctx. body= "333";
//console.log("创建集合!"+"logs");
const find= collection. find({ "repo" : "salary"});
const array= await find. toArray();
ctx. body= array;
console. log( ctx. body);

});

发现客户端用.then .catch 和import比较多,服务器端用async/await和require比较多, 

客户端的.then .catch用await代替看看。这样就和传统编程结构更接近了。

再比较下import和require的区别。

如果嵌套不深,用.then .catch也挺合适,嵌套多的话,用async和await 和try catch可能更易读。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值