Finding Reading Help from MongoDB in Node.JS

I have several entries stored in MongoDB. I am trying to display them in a browser window using the Node.JS http server. I think that I am a good part of the way, but I miss a few little things that keep her from real work.

The code below uses node-Mongo-native to connect to the database.

If there is anyone who can help me make the latest connections with working in node, I would really appreciate it. In fairness, I'm sure this is just the beginning.

var sys = require("sys"); var test = require("assert"); var http = require('http'); var Db = require('../lib/mongodb').Db, Connection = require('../lib/mongodb').Connection, Server = require('../lib/mongodb').Server, //BSON = require('../lib/mongodb').BSONPure; BSON = require('../lib/mongodb').BSONNative; var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; sys.puts("Connecting to " + host + ":" + port); function PutItem(err, item){ var result = ""; if(item != null) { for (key in item) { result += key + '=' + item[key]; } } // sys.puts(sys.inspect(item)) // debug output return result; } function ReadTest(){ var db = new Db('mydb', new Server(host, port, {}), {native_parser:true}); var result = ""; db.open(function (err, db) { db.collection('test', function(err, collection) { collection.find(function (err, cursor){ cursor.each( function (err, item) { result += PutItem(err, item); }); }); }); }); return result; } http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end("foo"+ReadTest()); }).listen(8124); console.log('Server running on 8124'); 

Sources: - mongo connection code: https://github.com/christkv/node-mongodb-native/blob/master/examples/simple.js - Node. http code: nodejs.org

EDIT CORRECTED CODE

Thanks to Mic below who made me move in the right direction. For anyone interested, a fixed solution is here:

 function ReadTest(res){ var db = new Db('mydb', new Server(host, port, {}), {native_parser:true}); var result = ""; res.write("in readtest\n"); db.open(function (err, db) { res.write("now open\n"); db.collection('test', function(err, collection) { res.write("in collection\n"); collection.find(function (err, cursor){ res.write("found\n"); cursor.each( function (err, item) { res.write("now open\n"); var x = PutItem(err, item); sys.puts(x); res.write(x); if (item == null) { res.end('foo'); } }); }); }); }); } http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.write("start\n"); ReadTest(res); }).listen(8124); console.log('Server running on 8124'); 
+4
source share
4 answers

I assume that you return the result, record the response and close the connection before anything gets out of db.

One solution would be to pass the response object to where you really need it, for example:

 function readTest(res) { db.open(function (err, db) { db.collection('test', function(err, collection) { collection.find(function (err, cursor) { res.writeHead(200, {'Content-type' : 'text/plain'}); cursor.each( function (err, item) { res.write(item); }); res.end(); ... 

Of course, you should also handle errors and try to avoid nesting too many levels, but this is another discussion.

+6
source

Instead of writing all the low-level Mongodb passcodes, you can try a simple library like mongous so that you can focus on your data and not on MongoDB morgues.

+1
source

You might want to try mongoskin .

+1
source

Reading documents

To apply special value filters, we can pass specific values ​​to the find() . Here is the SQL query:

SELECT * FROM Table1 WHERE name = 'ABC'

which is equivalent to the following in MongoDB ( Collection1 notification for Table1 ):

db.Collection1.find({name: 'ABC'})

We can bind count() to get the number of results, pretty() to get a readable result. The results can be further narrowed by adding additional parameters:

db.Collection1.find({name: 'ABC', rollNo: 5})

It is important to note that these filters are AND by default. To apply an OR filter, we need to use $or . These filters will be specified depending on the structure of the document. Example: for the attribute of the name object for the school object, we need to specify a filter, for example, "school.name" = 'AUHS'

We use the DOT notation here, trying to access the nested name field of the school field. Also note that filters are quoted , without which we get syntax errors.

You can match equality over arrays:

  • on all arrays
  • based on any item
  • based on a specific item
  • more complex matches using operators

In the following query:

db.Collection1.find({name: ['ABC','XYZ']})

MongoDB is going to identify documents by exact matching an array of one or more values. Now, for these types of queries, the order of the elements is important, which means that we will only match documents that ABC follow on XYZ , and these are only 2 elements of the name array

 {name:["ABC","GHI","XYZ"]}, {name:["DEF","ABC","XYZ"]} 

In the above document, we say that we need to get all the documents, where ABC is the first element. So, we will use the filter below:

db.Schools.find({'name.0': 'ABC' })

0
source

Source: https://habr.com/ru/post/1346388/


All Articles