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