无法使用身份验证制作基本的mongo shell脚本 [英] can't make basic mongo shell script with authentication

查看:40
本文介绍了无法使用身份验证制作基本的mongo shell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常复杂的问题,我认为我可以通过编写mongo shell脚本来解决,但我什至无法建立简单的连接.我有一个本地mongo数据库,该数据库需要我通常以这种方式访问​​的用户名/密码:

I have a really complicated issue that i think i can solve by writing a mongo shell script but i can't even manage to make a simple connection. I have a local mongo database which is requires a username/password that i normally access like this:

mongo admin -u <username> -p

在这一点上,我输入密码和万岁!我有一个贝壳.但这对我的问题不起作用.作为测试,我创建了一个名为test.js的文件,其内容如下:

at which point I enter the password and hooray! i have a shell. but that won't work for my issue. As a test, I created a file called test.js and all it has in it is this:

var conn = new Mongo()

db = conn.getDB("test");
db.cust.find();

然后我从命令行运行脚本,如下所示:

I then run the script from the command line like so:

mongo test.js

这点我明白了:

MongoDB shell version: 2.4.10
connecting to: test

为什么我没有结果?

推荐答案

我终于完成了这项工作.这就是我最终这样做的方式:

I finally made this work. This is how i ended up doing it:

首先,我创建了一个名为test.js的文件,其中包含以下内容:

First I made a file called test.js with the following in it:

db = connect("localhost:27017/admin");

db.auth('username','password');

db = db.getSiblingDB('test');

var cursor = db.cust.find();

while (cursor.hasNext()) {
   printjson(cursor.next());
}

然后我从命令行运行此命令:

I then ran this command from the command line:

mongo test.js

我还想向其他有问题的开发人员指出一些我学到的东西.

I also want to point out a few things that i learned while trying to do this to any other developer who is having issues.

1)如果添加新数据库,并且您正在使用身份验证运行mongo,则需要先登录到身份验证数据库,然后切换到所需的数据库(如我的示例所示),或者您需要添加用户/密码到所需的数据库(因为我可能首先应该这样做)

1) if you add a new database, and your are running mongo with authentication you either need to log into the authentication database first and then switch to the desired database (as my example shows) or you need to add a user/password to the desired database (as i probably should have done in the first place)

2)通过mongo运行javascript文件时,不要期望使用与您惯用的相同的"javascript"函数.我刚刚学到了一个很难的教训,即并非所有的javascript都是相同的.例如,您不能在通过mongo运行的javascript文件中使用Console.log(),因为console.log实际上不是核心javascript,而是特定于浏览器和节点实现的功能.

2) When running a javascript file via mongo, don't expect to use the same "javascript" functions that you are used to. I just learned a hard lesson that not all javascript is the same. for example, you can not use Console.log() in a javascript file that is run via mongo because console.log is not actually core javascript but rather a function specific to browser and node implementations.

这篇关于无法使用身份验证制作基本的mongo shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆