'MongoDB NodeJS error: assert.equal(3, result.result.n) not working. Giving error "Cannot read property 'n' of undefined"
I'm new to MongoDB and have just started setting up the insert document function in my js file. This is the code I copied from the documentation:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'FruitsDB';
const client = new MongoClient(url, {useNewUrlParser: true});
// Use connect method to connect to the server
client.connect(function(err) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
insertDocuments(db, function() {
client.close();
});
});
const insertDocuments = function(db, callback) {
// Get the documents collection
const collection = db.collection('fruits');
// Insert some documents
collection.insertMany([
{a : 1}, {a : 2}, {a : 3}
], function(err, result) {
assert.equal(err, null);
assert.equal(3, result.result.n);
assert.equal(3, result.ops.length);
console.log("Inserted 3 documents into the collection");
callback(result);
});
}
It gives an error saying "Cannot read property 'n' of undefined". Can someone help me out?
Solution 1:[1]
Replacing
assert.equal(3, result.result.n);
assert.equal(3, result.ops.length);
with
assert.equal(3,result.insertedCount);
assert.equal(3,Object.keys(result.insertedIds).length);
will do the magic.
According to the latest MongoDB Nodejs driver's documentation, the collection.insertMany() returns a Promise of type InsertManyResult. See the following api documentations link1 and link2 for more details.
Solution 2:[2]
Hey it seems that we are following the same tutorial: I'm using node v14.17.3 and mongodb 5.0.1
Commenting out is the only solution i found for the moment to get the needed console output:
//assert.equal(3, result.result.n);
//assert.equal(3, result.ops.length);
console output:
Connected successfully to server
Inserted 3 documents into the collection
Solution 3:[3]
If you comment it out, then even if you insert 2,3 or 4 number of documents it will still log "Inserted 3 documents into the collection"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anjana Sarath |
| Solution 2 | pnz |
| Solution 3 | Ahmad Ali |
