mongo导入js脚本(Mongo命令)遇到的问题
2022-04-21 本文已影响0人
mtinsky
记录在linux下执行mongo导入js脚本(Mongo命令)遇到的问题
- Unauthorized
- 现象
执行./mongo < test.js,如下报错
MongoDB shell version v3.4.23
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.23
2022-04-21T10:35:57.062+0800 E QUERY [thread1] Error: error: {
"ok" : 0,
"errmsg" : "not authorized on test to execute command { xxxxxxx }",
"code" : 13,
"codeName" : "Unauthorized"
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DBCommandCursor@src/mongo/shell/query.js:702:1
DBQuery.prototype._exec@src/mongo/shell/query.js:117:28
DBQuery.prototype.hasNext@src/mongo/shell/query.js:288:5
@(shell):1:7
2022-04-21T10:35:57.063+0800 E QUERY [thread1] TypeError: this._cursor is null :
DBQuery.prototype.close@src/mongo/shell/query.js:681:5
@(shell):1:1
bye
- 原因:需要使用账号密码访问库
- 解决: mongo 要访问的库 -u 账号 -p '密码'
- 参考:https://stackoverflow.com/questions/15272521/command-line-authentication-of-mongo-fails
- unterminated string literal
- 现象
执行./mongo < test.js,如下报错
MongoDB shell version v3.4.23
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.23
2022-04-21T09:11:06.308+0800 E QUERY [thread1] SyntaxError: unterminated string literal @(shellhelp1):1:24
error2:SyntaxError: unterminated string literal @(shellhelp1):1:24
bye
- 原因: 查看文件内容原本换行符为\r\n,即windows风格的换行符
- 解决: 将换行符\r\n 全局替换为\r即替换为Unix分格的换行符,解决
- 参考: https://stackoverflow.com/questions/49402772/issue-in-executing-mongo-commands-through-shell-script
- console is not defined
- 现象
执行./mongo < test.js,如下报错
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.23
2022-04-21T09:29:10.270+0800 E QUERY [thread1] ReferenceError: console is not defined :
@(shell):31:2
bye
- 原因: 脚本内使用了console.log("xxxx")打印日志
- 解决:将console.log("xxxx")改为print("")
- 参考:http://cn.voidcc.com/question/p-bvowdgaq-ky.html
- Mongodb的js脚本操作多个数据库
- 使用db.getSiblingDB( '数据库名' )或者db.getSisterDB( '数据库名' )
- 例子
# 加上有数据库dba和dbb,分别有集合ca,cb
db.getSiblingDB( 'dba' ).ca.find();
db.getSiblingDB( 'dbb' ).cb.find();