简体   繁体   中英

var usage in mongoDB

I am learning mongoDB by following the tutorial, http://docs.mongodb.org/manual/tutorial/getting-started/

However, the sample code, var c = db.testData.find() , confuses me. Without var, the execution just prints out the documents, with the var, c becomes the cursor. The other command, j = { name : "mongo" } , I don't see the difference with or without var. I want to be clear when I should have var and when I can ignore var.

I google the question little bit, for example, Difference between using var and not using var in JavaScript , it talks about scope. I cannot understand how my question relates to scope.

http://docs.mongodb.org/manual/tutorial/iterate-a-cursor/

According to this doc,

However, in the mongo shell, if the returned cursor is not assigned to a variable using the var keyword, then the cursor is automatically iterated up to 20 times to print up to the first 20 documents in the results.

From the mongo getting started tutorial:

This tutorial provides an introduction to basic database operations using the mongo shell. mongo is a part of the standard MongoDB distribution and provides a full JavaScript environment with a complete access to the JavaScript language and all standard functions as well as a full database interface for MongoDB. See the mongo JavaScript API documentation and the mongo shell JavaScript Method Reference.

Source: http://docs.mongodb.org/manual/tutorial/getting-started/

In Javascript it's best practice to not use global variables. You define global variables without the var prefix and local variables with the var prefix. I guess the Javascript implementation in Mongo disabled global variables completely because it's bad practice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM