【问题标题】:findOne NodeJS MongoDB driverfindOne NodeJS MongoDB 驱动程序
【发布时间】:2013-10-28 01:18:13
【问题描述】:

我在一个名为“English”的集合中拥有如下所示的 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


    【解决方案1】:

    nodejs mongodb findOne by 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
      });
    

    【讨论】:

      【解决方案2】:

      问题是其中一个参数的拼写错误(“res”中有一个额外的“t”)。而不是

      app.get('/sentences/:id', function(req,rest){
      ...
      
      res.send(item);
      

      应该是

      app.get('/sentences/:id', function(req,res){ 
      ...
      
      res.send(item);
      

      【讨论】:

        【解决方案3】:

        虽然不好,但仍会对其他人有所帮助。

        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
          });
        

        【讨论】:

        • 为什么要复制已有的答案?
        猜你喜欢
        • 2014-06-29
        • 2016-03-13
        • 2021-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-03
        相关资源
        最近更新 更多