我有一个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
消息。 最佳答案
node.js mongodb findOne通过ID
时间已晚,但会对其他人有所帮助。
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
});
关于node.js - findOne NodeJS MongoDB驱动程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19625827/