简体   繁体   中英

Can not find data from collection in mongodb

I am trying practice mongodb in node.js. I am successfully connecting the database, inserting into the database but I cant get data from database. Here is my code:

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);
    });

});

You're running into a problem with the asynchronous nature of Node.js. If you run this, it's possible for collection.find to complete before collection.insert. Try this instead.

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);
        });
    });
});

By putting the find inside the callback from the insert, you're guaranteeing that the find doesn't run until the insert is actually finished.

Try this

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);
  });
}

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