![](/img/trans.png)
[英]Query MongoDb by date range using FindOne (via Nodejs native driver)
[英]findOne NodeJS MongoDB driver
我有 JSON 数据,就像您在下面一个名为“英语”的集合中看到的那样,我正在使用 MongoDB 驱动程序设置带有 nodejs 应用程序的 REST api。 如果我执行以下操作,我将获得浏览器中返回的所有 JSON 数据。
app.get('/sentences', function (req, res){
db.collection('english', function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
})
但是,当我尝试转到/sentences/1
获取一条记录时,该应用程序冻结(浏览器选项卡中的半月转得很慢)并且没有记录任何错误。 我做这个 findOne 的方式有什么问题吗?
app.get('/sentences/:id', function(req,rest){
var query = { 'question' : req.params.id };
console.log(query);
console.log('query');
db.collection('english', function(err, collection) {
collection.findOne(query, function(err, item) {
console.log(err);
res.send(item);
});
});
});
JSON 数据
[
{
"_id": "526c0e21977a67d6966dc763",
"question": "1",
"uk": "blah blah blah",
"us": "blah blah balh"
},
{
"_id": "526c0e21977a67d6966dc764",
"question": "2",
"uk": "Tom went outside for a fag. I think he smokes too much!",
"us": "Tom went outside for a cigarette. I think he smokes too much!"
},
{
"_id": "526c0e21977a67d6966dc765",
"question": "3",
"uk": "Do you fancy going to the cinema on Friday?",
"us": "How about going to the movies on Friday"
}
]
更新
发生的事情是应用程序最终超时,我在浏览器中No data received
一条No data received
消息。
为时已晚,但会对其他人有所帮助。
var id = new require('mongodb').ObjectID('58fcf02b1ab5de07e2a1aecb');//req.params.id
db.collection('users').findOne({'_id':id})
.then(function(doc) {
if(!doc)
throw new Error('No record found.');
console.log(doc);//else case
});
问题是其中一个参数的拼写错误('res' 中的一个额外的 't')。 代替
app.get('/sentences/:id', function(req,rest){
...
res.send(item);
本来应该
app.get('/sentences/:id', function(req,res){
...
res.send(item);
这不好,但仍然会对其他人有所帮助。
var id = new require('mongodb').ObjectID('58fcf02b1ab5de07e2a1aecb');//req.params.id
db.collection('users').findOne({'_id':id})
.then(function(doc) {
if(!doc)
throw new Error('No record found.');
console.log(doc);//else case
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.