无法在mongodb中找到集合中的数据

时间:2014-11-22 06:06:04

标签: node.js mongodb database

我正在尝试在node.js中练习mongodb。我成功连接数据库,插入数据库,但我无法从数据库中获取数据。这是我的代码:

var mongo = require("mongodb");
var host = '127.0.0.1';
var port = 1337;
var db = new mongo.Db('nodejs-introduction', new mongo.Server(host, port, {}));

db.open(function(error, dbClient) {
    console.log('We are connected');

});

var collection = db.collection('user');
collection.insert({
    id: "1",
    name: "Musa",
    twitter: "puzzlemusa",
    email: "puzzlemusa@gmail.com"
}, function(error) {
    console.log('Successfully inserted Musa');
});

collection.find({id: "1"}, function(err, cursor) {
    cursor.toArray(function(err, users){
        console.log("Found the following records", users);
    });

});

2 个答案:

答案 0 :(得分:1)

您遇到了Node.js异步性质的问题。如果你运行它,collection.find可以在collection.insert之前完成。试试这个。

var mongo = require("mongodb");
var host = '127.0.0.1';
var port = 1337;
var db = new mongo.Db('nodejs-introduction', new mongo.Server(host, port, {}));

db.open(function(error, dbClient) {
    console.log('We are connected');

});

var collection = db.collection('user');
collection.insert({
    id: "1",
    name: "Musa",
    twitter: "puzzlemusa",
    email: "puzzlemusa@gmail.com"
}, function(error) {
    console.log('Successfully inserted Musa');

    collection.find({id: "1"}, function(err, cursor) {
        cursor.toArray(function(err, users){
            console.log("Found the following records", users);
        });
    });
});

通过将查找放入插入回调中,您可以保证查找不会在插入实际完成之前运行。

答案 1 :(得分:1)

试试这个

var mongo = require("mongodb");

var host = '127.0.0.1';
var port = '27017';    // this is my port, change to 1337

var db = new mongo.Db('nodejs-introduction', new mongo.Server(host, port));

db.open(function(err, db) {
  if (err) {
    return console.log(err);
  }

  var collection = db.collection('user');

  insert(collection);

  // find(collection);
});


function insert(collection) {
  collection.insert({
      id: "1",
      name: "Musa",
      twitter: "puzzlemusa",
      email: "puzzlemusa@gmail.com"
  }, function (error) {
      if (error) {
        return console.log(error);
      }

      console.log('Successfully inserted Musa');

      find(collection);
  });
}

function find(collection) {
  collection.find({id: '1'}).toArray(function(err, users) {
    console.log(users);
  });
}