MongoDb find()返回许多不需要的字段

时间:2015-12-25 08:50:44

标签: node.js mongodb rest

 app.get('/',function(req,res){
        var response={};
        db.collection('first').find({},function(err,result){
            if(err){
                db.close();
                console.log('Error');
                console.log(err);
            }
            else{
                db.close();
                console.log('Success');
                console.log(response);
            }
        });

        res.end(response);
    });

但是,这会返回大量不需要的数据。我也查看了这些数据,但是我没有看到集合中的条目值/字段。我希望它仅将字段值作为JSON对象返回。我该怎么做?

示例输出:(发布所有内容太多)

Readable {
  connection: null,
  server: null,
  disconnectHandler: 
   { s: { storedOps: [], storeOptions: [Object], topology: [Object] },
     length: [Getter] },
  bson: {},
  ns: '****',
  cmd: 
   { find: '******',
     limit: 0,
     skip: 0,
     query: {},
     slaveOk: true,
     readPreference: { preference: 'primary', tags: undefined, options: undefined } },
  options: 
   { skip: 0,
     limit: 0,
     raw: undefined,
     hint: null,
     timeout: undefined,
     slaveOk: true,
     readPreference: { preference: 'primary', tags: undefined, options: undefined },
     db: 
      EventEmitter {
        domain: null,
        _events: {},
        _eventsCount: 0,
        _maxListeners: undefined,
        s: [Object],
        serverConfig: [Getter],
        bufferMaxEntries: [Getter],
        databaseName: [Getter],
        options: [Getter],
        native_parser: [Getter],
        slaveOk: [Getter],
        writeConcern: [Getter] },
     promiseLibrary: [Function: Promise],
     disconnectHandler: { s: [Object], length: [Getter] } },
  topology: 
   EventEmitter {
     domain: null,
     _events: 
      { reconnect: [Function],
        timeout: [Object],
        error: [Object],
        close: [Function],
        destroy: [Object] },
     _eventsCount: 5,
     _maxListeners: undefined,

以及更多......

谢谢。

1 个答案:

答案 0 :(得分:6)

首先,您要记录并发回一个空的response对象。您的问题来自语法,find()只接受一个参数并返回一个游标,您必须在循环内调用next()来获取每个文档或调用toArray()来获取所有文档马上:

app.get('/', function (req, res) {
    db.collection('first').find({}).toArray(function (err, docs) {
        db.close();

        if (err) {
            console.log('Error');
            console.log(err);
            res.end();
        }
        else {
            console.log('Success');
            console.log(docs);
            res.json(docs);
        }
    });
});