mongo --shell file.js and “use” statement

大兔子大兔子 提交于 2019-12-10 14:52:48

问题


can't find solution for simple question:

I have file text.js

use somedb
db.somecollection.findOne()

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

it's work properly

But when I try this way

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

I got this error message

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

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?

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. right after posting this question I find sollution for SublimeText2:

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

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

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

this build tool work properly


回答1:


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.

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 // 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.

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




回答2:


You can specify the database while starting the mongo client:

mongo somedb text.js

To get the output from the client to stdout just use the printjson function in your script:

printjson(db.somecollection.findOne());



回答3:


Mongo needs to be invoked from a shell to get that mode, with Ansible you would have this:

- name: mongo using different databases
  action: shell /usr/bin/mongo < text.js

Instead of this:

- name: mongo breaking
  command: /usr/bin/mongo < text.js



回答4:


This is what finally worked for me on Windows + Sublime Text 2 + MongoDB 2.6.5

{
    "selector": "source.js",
    "shell":true,
    "cmd": ["mongo","<", "$file"],
    "working_dir" : "C:\\MongoDB\\bin"
} 


来源:https://stackoverflow.com/questions/13725904/mongo-shell-file-js-and-use-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!