I am trying to save and read some data from MongoDB using standard MongoClient and pure NodeJS. The fact is that I can write data, but not read . 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;
});
Reading function
function selectDB(tableName, key, value, callback) {
var req = {};
req[key] = value;
db.collection(tableName).find(req, callback);
}
Recording function
function insertDB(tableName, obj) {
db.collection(tableName).insertOne(obj, function (err, res) {
if (err !== null) {
throw err;
} else {
console.log(res);
}
});
}
After I inserted the data into db using this, it can be found using the Mongo shell. I use the bash find()function in the shell successfully, but not in the js code.
Update
Now I pass the callback to the function toArray()as indicated here, but I still don't get the result: the callback is not being executed. My function selectDB()now looks like this.
var req = {};
req[key] = value;
db.collection(tableName).find(req).toArray(callback);
Update
Here is a sample data example: Shell Input:
> db.users.find({"email":"aa@aa"})
Conclusion:
{ "_id" : ObjectId("572ba1a599f59780f549e5e3"), "email" : "aa@aa", "password" : "2GU9I8syq2Oyf6rSqJNDVyFPOTRwPg3nyQjSwPXppvM=" }
Js
( req):
key = "email"
value = "aa@aa"
, .
, (callback):
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();
}
});
, .
error() , undefined.
- , , , .