No data present after successful insert

20 views
Skip to first unread message

den...@replex.io

unread,
Sep 20, 2017, 6:29:14 PM9/20/17
to mongodb-user
Hi,
I'm trying to insert some data into MongoDB but even though the write is acknowledged as successful when I read the collection
afterwards sometimes no data is returned. The Code looks like this:

function insertUser(db, callback) {
   
var documents = require('./data/index').user;
    db
.collection('user').insertMany(documents, {w:1}, function(err, records) {
       
if (err) {
            callback
(err);
       
} else {
            console
.log(records);

            db
.collection('user').find().toArray((err, res) => {
               
if (err) {
                    console
.log('err: ' + err);
               
} else {
                    console
.log(res);
               
}
                callback
(null);
           
});
       
}
   
});
}


The insert succeeds and the records result shows that two records were inserted.
The following find() succeeds as well but sometimes res is just an empty array as if this is an empty collection.
MongoDB is set up as a primary for a replica set but currently there is no secondary connected in case
that matters.
Any ideas what could be going on here?

Regards,
  Dennis

Kevin Adistambha

unread,
Oct 4, 2017, 1:49:30 AM10/4/17
to mongodb-user

Hi,

What is the content of your ./data/index file? I tried a similar construct using your code by hardcoding documents and it seems to work as expected. Here’s the complete code I tried:

var MongoClient = require('mongodb').MongoClient;

function insertUser(db, callback) {
    var documents = [{'a':1}, {'a':2}];
    db.collection('user').insertMany(documents, {w:1}, function(err, records) {
        
if (err) {
            callback(err);
        } else {
            console.log(records);

            db.collection('user').find().toArray((err, res) => {
                if (err) {
                    console.log('err: ' + err);
                } else {
                    console.log(res);
                }
                callback(null
);
            });
        }
    });
}

MongoClient.connect('mongodb://localhost/test', function(err, conn) {
    if (err) { console.log(err) }
    insertUser(conn.db('test'), function(err, res) {
        if (err) { console.log(err) }
        console.log('inserts done');
        conn.close();
    })
})

If you’re still having issues, please post a runnable self-contained script similar to the one above, along with your MongoDB version and your driver version.

Best regards
Kevin

Reply all
Reply to author
Forward
0 new messages