简体   繁体   中英

How can I read data from MongoDB via pure NodeJS?

I'm trying to save and read some data from a MongoDB using standard MongoClient and pure NodeJS. The thing is that I can write data but not read it. Here is my code.

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/test";
var db;

MongoClient.connect(url, function (err, database) {
    if (err !== null) {
        throw err;
    }
    db = database;
});

Read function

function selectDB(tableName, key, value, callback) {
    var req = {};
    req[key] = value;
    db.collection(tableName).find(req, callback);
}

Write function

function insertDB(tableName, obj) {
    db.collection(tableName).insertOne(obj, function (err, res) {
        if (err !== null) {
            throw err;
        } else {
            console.log(res);
        }
    });
}

After I've inserted data into db using this, it can be found using Mongo shell. I use bash find() function in the shell successfully but not in the js code.

Update

Now I pass the callback to the toArray() function as mentioned here, but I still get no result: the callback is not executed. My selectDB() function now looks like this.

var req = {};
req[key] = value;
db.collection(tableName).find(req).toArray(callback);

Update

Here is some data query example: Shell Input:

> db.users.find({"email":"aa@aa"})

Output:

{ "_id" : ObjectId("572ba1a599f59780f549e5e3"), "email" : "aa@aa", "password" : "2GU9I8syq2Oyf6rSqJNDVyFPOTRwPg3nyQjSwPXppvM=" }

JS

Query (key value pair for the req variable):

key = "email" value = "aa@aa"

After that I get the results I described before.

Update

After all here is my result handling code ( callback ):

//select() here is an alias for selectDB() function declared earlyer
db.select("users", "email", user.email, function (err, cursor) {
        if (cursor === undefined || cursor == null || err !== null) {
            error();
        } else if (cursor.password === user.password) {
            success();
        } else {
            wrong();
        }
    });

Finally the callback is executed. The error() function is always executed since cursor in the callback always undefined.

If somebody knows what I'm doing wrong and how to fix it, please answer.

What version of the node-mongodb-native (the driver) are you using? In the latest one find does not accept callback as the second argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM