Reputation: 111
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: "[email protected]"
}, 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);
});
});
Upvotes: 0
Views: 1737
Reputation: 77482
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: "[email protected]"
}, 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);
});
}
Upvotes: 1
Reputation: 23060
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: "[email protected]"
}, 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.
Upvotes: 1