0
votes

i just searched for my problems around in the stackoverflow's discussions but nothings similar with my issued. So, in this case, i just want to update my collection and then use the 'Promise' module instead use the callbacks / anonymous functions as normally i did. but the error comes up when I execute the js's application in cmd.

Here my simple code:

var Promise = require('promise'); // use the 'promise' module
    var MongoClient = require('mongodb').MongoClient;
    var url = 'mongodb://localhost/EmployeeDB';

    MongoClient.connect(url)
    	.then(function(err, db) {
    	    db.collection('Employee').updateOne({
    	        "EmployeeName": "Jeffrey"
    	    }, {
    	        $set: {
    	            "EmployeeName": "Jeffrey Scurgs"
    	        }
    	    });
    	}); 

and the error results when i executed the code in cmd:

(node:8600) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'collection' of undefined at C:\Users\DELL\guru99\5_Promise\app_promise.js:7:9 at at process._tickCallback (internal/process/next_tick.js:189:7) (node:8600) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:8600) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

so, is there any wrong code in my code above?

thanks for helping... sorry for my bad english

2
db is undefined so check the content of errAndreas
Have you checked your err object to see if there might be an error?Faz

2 Answers

1
votes

Your approach is correct but you a missed one thing.

When you don't provide callback parameters mongo ORM return a promise. Here is the corrected code:

MongoClient.connect(url)
    .then(function(db) { // <- db is first argument
        db.collection('Employee').updateOne({
            "EmployeeName": "Jeffrey"
        }, {
            $set: {
                "EmployeeName": "Jeffrey Scurgs"
            }
        });
    })
    .catch(function (err) {})
0
votes

The db variable can only be undefined if there was an error connecting to the database.

You need to check and fix any error shown. You can also share the error

var Promise = require('promise'); // use the 'promise' module
    var MongoClient = require('mongodb').MongoClient;
    var url = 'mongodb://localhost/EmployeeDB';

    MongoClient.connect(url)
    	.then(function(err, db) {
            if (err) {
              return throw err; // Check the error
            }
    	    db.collection('Employee').updateOne({
    	        "EmployeeName": "Jeffrey"
    	    }, {
    	        $set: {
    	            "EmployeeName": "Jeffrey Scurgs"
    	        }
    	    });
    	});