mongo --shell file.js和"use"陈述 [英] mongo --shell file.js and "use" statement

查看:158
本文介绍了mongo --shell file.js和"use"陈述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

找不到简单问题的解决方案:

can't find solution for simple question:

我有文件 text.js

use somedb
db.somecollection.findOne()

当我使用来自文件的重定向命令在cmd中运行此文件时: "mongo< text.js"

When I run this file in cmd with redirection command from file: "mongo < text.js"

正常工作

但是当我尝试这种方式

"mongo text.js"或"mongo --shell test.js"

"mongo text.js" or "mongo --shell test.js"

我收到此错误消息

MongoDB Shell版本:2.2.0 连接到:测试 键入帮助"以获取帮助 星期三十二月05 16:05:21语法错误:丢失;语句之前 pathToFile \ test.js.js:1 加载失败: pathToFile \ test.js.js

MongoDB shell version: 2.2.0 connecting to: test type "help" for help Wed Dec 05 16:05:21 SyntaxError: missing ; before statement pathToFile\test.js.js:1 failed to load: pathToFile\test.js.js

使用somedb"失败.如果我删除此行,则可以正常运行,但是控制台很清楚.

It's fail on "use somedb". If I remove this line, it's run without error, but console is clear.

有什么想法,这是什么以及如何解决?

is there any idea, what is this and how to fix?

我想为此找到解决方案,以创建Sublime Text 2的构建工具. 默认的构建文件是

I'm tying to find sollution for this, to create build tool for Sublime Text 2. default build file was

{
"cmd": ["mongo","$file"]
}

但是在这种情况下,我得到了上面的错误

but in this case I get the error above

PS.在发布此问题后,我立即找到了解决方案 SublimeText2 :

PS. right after posting this question I find sollution for SublimeText2:

{
"selector": "source.js",
"shell":true,
"cmd": ["mongo < ${file}"]
}

PSS.在发布此问题后,我立即找到了解决方法 SublimeText3 :

PSS. right after posting this question I find sollution for SublimeText3:

{
"selector": "source.js",
"shell":true,
"cmd": ["mongo","<", "$file"]
}

此构建工具正常工作

推荐答案

use dbname是交互式shell中的帮助程序功能,当您将mongo shell与像您一样的JS脚本文件一起使用时,该功能不起作用.

use dbname is a helper function in the interactive shell which does not work when you are using mongo shell with a JS script file like you are.

对此有多种解决方案.最好的IMO是这样,将数据库名称以及主机名和端口名显式传递给mongo:

There are multiple solutions to this. The best one, IMO is to explicitly pass the DB name along with host and port name to mongo like this:

mongo hostname:27017/dbname mongoscript.js//将27017替换为您的端口号

mongo hostname:27017/dbname mongoscript.js // replace 27017 with your port number

一种更好的方法是在脚本的开头定义数据库:

A better way to do this would be to define the DB at the beginning of your script:

mydb=db.getSiblingDB("yourdbname");
mydb.collection.findOne();
etc.

后者是可取的,因为它允许您在同一脚本中与多个DB进行交互.

The latter is preferable as it allows you to interact with multiple DBs in the same script if you need to do so.

这篇关于mongo --shell file.js和"use"陈述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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