I am getting an error from a Node app. I search from internet but no solution found, everything is same like video I have watched, in video there is no err, but in my code this error occurred again and again,
This is my app.js
//jshint esversion:6
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'fruitsDB';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("Connected correctly to server");
const db = client.db(dbName);
// Insert a single document
db.collection('inserts').insertOne({a:1}, function(err, r) {
assert.equal(null, err);
assert.equal(1, r.insertedCount);
// Insert multiple documents
db.collection('inserts').insertMany([{a:2}, {a:3}], function(err, r) {
assert.equal(null, err);
assert.equal(2, r.insertedCount);
client.close();
});
});
});
when I type to gitbash node app.js this err occured this is console
$ node app.js
Connected correctly to server
node:assert:123
throw new AssertionError(obj);
^
AssertionError [ERR_ASSERTION]: 1 == undefined
at D:\text editor\web_pros\FruitsProject\app.js:21:12
at D:\text editor\web_pros\FruitsProject\node_modules\mongodb\lib\utils.js:5
10:9
at D:\text editor\web_pros\FruitsProject\node_modules\mongodb\lib\operations
\execute_operation.js:48:55
at D:\text editor\web_pros\FruitsProject\node_modules\mongodb\lib\utils.js:5
10:9
at completeEndSession (D:\text editor\web_pros\FruitsProject\node_modules\mo
ngodb\lib\sessions.js:147:17)
at D:\text editor\web_pros\FruitsProject\node_modules\mongodb\lib\sessions.j
s:157:13
at maybePromise (D:\text editor\web_pros\FruitsProject\node_modules\mongodb\
lib\utils.js:496:5)
at ClientSession.endSession (D:\text editor\web_pros\FruitsProject\node_modu
les\mongodb\lib\sessions.js:133:41)
at D:\text editor\web_pros\FruitsProject\node_modules\mongodb\lib\operations
\execute_operation.js:48:36
at D:\text editor\web_pros\FruitsProject\node_modules\mongodb\lib\operations
\insert.js:53:13 {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: 1,
expected: undefined,
operator: '=='
}
I watch older videos and try to connect app to database. maybe there is some updates
The result of the method insertOne
doesn't have the property insertedCount
because if it succeeds the number of inserted documents will by definition be 1
.
If the database can't insert the document, it will call the callback with a non-null error. This applies to both general errors as well as duplicate keys.
Therefore the assert.equal(null, err)
already checks for what you want assert.equal(1, r.insertedCount)
to check. You can just remove that insertedCount
assertion.
Note that the insertedCount
property exists for insertMany
, so the assertion there is valid.