为什么我不能通过使用node.js将对象插入mongodb?

时间:2012-08-14 03:21:40

标签: node.js mongodb

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

我尝试将对象插入数据库。通过每次使用“console.log(array)”,我发现它总是“未定义”。它是否无法插入数据库或无法从数据库中找到。我怎么解决呢?

但是,'console.log(item)'显示'null'。它是否成功插入数据库,或者我应该改变另一种方式从数据库中获取对象。

1 个答案:

答案 0 :(得分:2)

collection.findOne是异步的,因此您不使用函数的返回值;相反,你应该从你(当前为空)的回调中console.log(item)

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