node.js と Mongodb パッケージを使用して MongoDB データベースにクエリを実行できません。
次のように 2 つのオブジェクトを正常に挿入しました。
var mongo = require("mongodb");
var host = "127.0.0.1";
var port = mongo.Connection.DEFAULT_PORT;
var db = new mongo.Db("nodejs-introduction", new mongo.Server(host, port, { }), {safe: true});
console.log(host);
db.open(function(error) {
console.log("We are connected ", + host + ':' + port);
db.collection("user", { w:1 }, function(error, collection){
console.log("We have the collection");
collection.insert({
id: "1",
name: "Foo Bar",
twitter: "Foo_Bar",
email: "info@nfoobar.com"
}, {w:1}, function() {
console.log("Succesfully inserted Foo Bar");
});
collection.insert({
id: "2",
name: "Bar Foo",
twitter: "Bar_Foo",
email: "info@tbarfoo.com"
}, {w:1}, function() {
console.log("Succesfully inserted Bar Foo");
});
});
});
ここではすべてうまくいき、エラーはありません。しかし、次のようにアイテムをクエリしたい場合:
var mongo = require("mongodb");
var host = "127.0.0.1";
var port = mongo.Connection.DEFAULT_PORT;
var db = new mongo.Db("nodejs-introduction", new mongo.Server(host, port, { }), {safe: false});
console.log(host);
db.open(function(error) {
console.log("We are connected ", + host + ':' + port);
//collection is sort of table
db.collection("user", function(error, collection){
console.log("We have the collection");
collection.find({ "id": "1" }, function(error, cursor){
cursor.toArray(function(error, users){
if (users.length == 0) {
console.log("no user found");
} else {
console.log("Found a user", users[0]);
}
});
});
});
});
次に、次のエラーが表示されます。
127.0.0.1
We are connected NaN:27017
We have the collection
/path/to/query.js:14
if (users.length == 0) {
^
TypeError: Cannot read property 'length' of null
だから私が理解しているのは、変数 users が null であり、一致するものを見つけることができないということですが、その理由はわかりません。何が間違っているのですか?