MaryHo
MaryHo

Reputation: 15

why can't I insert object into mongodb by using node.js?

    var express = require('express');
    var routes = require('./routes');
    var socket = require('socket.io');
    var fs = require('fs');
    var app = module.exports = express.createServer();
    var Server = require('mongodb').Server,
        Db = require('mongodb').Db,
        Connection = require('mongodb').Connection;
    var host = 'localhost';
    var port = Connection.DEFAULT_PORT;
    var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:false});

    db.open(function(err, db) {
        console.log('opened');   
        app.listen(3000); 

    });


    db.collection('locations', function(err, collection) {
          var object= {word:'TEST'};
          collection.insert(object, {safe:true}, function(err, result) {
            var array = collection.findOne({word:'TEST'}, function(err, item) {});            
             console.log(array);// <----always  "undefined" 
          });        
    });

I try to insert the object into the database. And by using "console.log(array)" everytime,I find that it always be "undefined". Is it can't be insert into the database or can't be found from the database. How can I solve it??

But, The 'console.log(item)' shows 'null'. So does it sucessfully insert into the database, or should I change another way to get the object from database.

Upvotes: 1

Views: 1711

Answers (1)

Michelle Tilley
Michelle Tilley

Reputation: 159095

collection.findOne is asynchronous, so you don't use the return value of the function; instead, you should console.log(item) from inside your (currently empty) callback.

 db.collection('locations', function(err, collection) {
     var object= {word:'TEST'};
     collection.insert(object, {safe:true}, function(err, result) {
       collection.findOne({word:'TEST'}, function(err, item) {
          console.log(item);
       });
     });        
 });

Upvotes: 2

Related Questions