![](/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.