Node JS: Do not embed in mongodb

So, I am following the Node.js training course at tutsplus.com, which so far has been wonderful.

I am participating in a MongoDB lesson and I peeled off a bit. I am not sure why this does not work for me as it works in the video and my code is the same. All I can imagine is an update, since the course was made a year ago.

From trying to console.log at different points, I think that the data is not inserted correctly at the beginning and therefore nothing is returned.

Everything seems to work as expected, except for the callback for cursor.toArray() .

I am currently studying node and mongodb, so please bear with me if I make an obvious mistake.

I was instructed to write the following file, and then execute it on the command line.

EDIT:

I narrowed down the problem to an insert script. When inserting data through the CLI, it will return it back.

 var mongo = require('mongodb'), host = "127.0.0.1", port = mongo.Connection.DEFAULT_PORT, db = new mongo.Db('nodejsintro', new mongo.Server(host, port, {})); db.open(function(err){ console.log("We are connected! " + host + " : " + port); db.collection("user", function(error, collection){ console.log(error); collection.insert({ id: "1", name: "Chris Till" }, function(){ console.log("Successfully inserted Chris Till") }); }); }); 
+4
source share
1 answer

Are you sure you really connected to mongo? When you connect to mongo from cli and type "show dbs", do you see nodejsintro? Is there a collection?

Also from your code

 db.open(function(err){ //you didn't check the error console.log("We are connected! " + host + " : " + port); db.collection("user", function(error, collection){ //here you log the error and then try to insert anyway console.log(error); collection.insert({ id: "1", name: "Chris Till" }, function(){ //you probably should check for an error here too console.log("Successfully inserted Chris Till") }); }); }); 

If you have already adjusted the logging and are sure that you are not getting any errors, try changing some connection information.

 var mongo = require('mongodb'); var Server = mongo.Server, Db = mongo.Db, BSON = mongo.BSONPure; var server = new Server('localhost', 27017, {auto_reconnect: true}); db = new Db('nodejsintro', server); db.open(function(err, db) { if (!err) { console.log("Connected to 'nodejsintro' database"); db.collection('user', {strict: true}, function(err, collection) { if (err) { console.log("The 'user' collection doesn't exist. Creating it with sample data..."); //at this point you should call your method for inserting documents. } }); } }); 
+2
source

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


All Articles