在Node.js中显示完整的MongoDB内容API
问题描述:
首先,别担心,它是一个很小的数据集 - 我意识到通过API将整个生产数据库转储到单个屏幕并不明智...我只需要通过Node.js应用程序中的API端点获取整个(小)DB的JSON转储。在Node.js中显示完整的MongoDB内容API
我的应用程序使用此代码并成功返回单记录:
MongoClient.connect("mongodb://localhost:27017/search", function (err, db) {
if(err) throw err;
db.collection('results', function(err, collection) {
// search for match that "begins with" searchterm
collection.findOne({'string':new RegExp('^' + searchterm, 'i')}, function(err, items){
// get result
var result;
if (items == null || items.result == null){
result = "";
}
else {
result = items.result;
}
// return result
res.send(result);
});
});
});
所以我知道节点成功地交谈蒙戈,但我该如何调整这个查询/代码基本上返回时,你执行得什么MongoDB命令行上的以下内容:
$ db.results.find()
答
感谢球员们,我感谢你的回答,指出我在正确的方向,就使用{}作为查询而言。下面是最终为我工作的代码:
db.collection('results', function(err, collection) {
collection.find({}).toArray(function(err, docs) {
res.send(docs);
});
});
的关键要素作为指定者(...)一部分。
答
这是代码段。
model.find({}).exec(function (err, result) {
if (err) {console.error(err); return;}
else return result;
});
首先使用您的预定义模型并调用find。逻辑是放置一个空对象{}
实质上呈现。从这个模型中选择全部。
有意义吗?
+0
我也推荐使用promises和mongodb。最好是蓝鸟。 – Remario
答
正如你所描述的那样。
collection.find({}).exec((err, result) => {
if (err) {
console.log(err);
return;
}
if (result.length > 0) {
// We check that the length is > 0 because using .find() will always
// return an array, even an empty one. So just checking if it exists
// will yield a false positive
res.send(result);
// Could also just use `return result;`
});
我很好奇你为什么需要加上'toArray'。介意分享您使用的MongoDB/Mongoose的版本? –
我说实话,我不知道猫鼬是什么。我在Mac OS X Sierra上运行MongoDB v3.2.0。我习惯了阵列(...),因为经过大量的随机试验和错误,这是第一件有效的工作。如果你建议一个正确的选择,我会给出一个去。 – HomerPlata
Mongoose是一个用于JavaScript/Node.js的MongoDB包装器,可以将东西抽象成更易于维护和可读的代码。我认为这就是为什么我建议的解决方案不起作用。 Mongoose可能正是你所做的:'toArray()'在内部。 –