最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

MongoDB find()到JSON NodeJS

运维笔记admin10浏览0评论

MongoDB find()到JSON NodeJS

MongoDB find()到JSON NodeJS

我是NodeJS的新手,我试图连接到MongoDB,我准备了一个查询,并且可以通过游标查看服务器上的输出。但是我想将find()的输出发送给响应。

var cursor = db.collection('dbLocations').find(
         {$and: [

         {type: locationType}
, 
    {createdAt : {"$gte": new Date(createdAt),
            "$lt": date1}}

      ]}
      ).skip(skip).limit(count);

现在我收到类似Cannot set headers after they are sent to the client如果我执行字符串连接,然后执行JSON.stringify我尝试了pretty(),但它给了我错误skip(...).limit(...).toString(...).pretty is not a function or skip(...).limit(...).pretty is not a function。我完全不知道如何转换,因为我对callback()的概念不清楚,而所有解决方案都有。是否有简单的字符串化,解析或相当不错的解决方案。下面是我的快速摘录,现在看起来很混乱。我想发送find()输出而不是随机的东西。

app.get('/api/first', function(request, response) {
    response.writeHead(200, {'Content-Type': 'application/json'});
    var locationType = request.body.type;
    var createdAt = request.body.createdAt;
    //var pageNumber = parseInt(request.body.pageNumber);
    console.log(locationType);
    console.log(createdAt);
    //console.log(pageNumber);
    var date1 = new Date(createdAt);
    date1.setDate(date1.getDate() + 1);
    var count = 2;
    var str="";
    var skip;
    if(request.body.pageNumber)
        skip = parseInt((request.body.pageNumber-1)*count);
    else
        skip = 0;
    MongoClient.connect(url, function(err, client) {
    if (err) throw err;
    console.log('Connected');
    var db = client.db('locationapi');
    var cursor = db.collection('dbLocations').find(
         {$and: [

         {type: locationType}
, 
    {createdAt : {"$gte": new Date(createdAt),
            "$lt": date1}}

      ]}
      ).skip(skip).limit(count);

        cursor.each(function(err, doc) {

        if(err) throw err;
  if(doc !== null) {console.log(doc); str=str+doc;}

  else client.close();
    });

    client.close();
});
        var myObj = {
            name: 'jgj',
            job: 'Ninja'
    };   // random stuff
    response.end(JSON.stringify(myObj));
});
回答如下:
db.collection('dbLocations').find({
  $and: [{
    type: locationType
  }, {
    createdAt: {
      "$gte": new Date(createdAt),
      "$lt": date1
    }
  }]
}, {
  skip: skip, 
  limit: count
}).toArray(function (err, docs) { 
  if (err) return res.status(500).send({error: err})
  res.send(docs)
});

https://mongodb.github.io/node-mongodb-native/3.3/quick-start/quick-start/#find-documents-with-a-query-filter

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论