【问题标题】:get collection data in nodejs and mongodb在 nodejs 和 mongodb 中获取集合数据
【发布时间】:2013-02-14 19:13:02
【问题描述】:

请告诉我,如何在客户端使用主干应用程序和服务器端使用 nodejs + mongodb 创建 REST API。

我是 nodejs 的新手,无法理解所有基本的东西。

举个例子——我需要收集朋友。 在我的客户端应用程序中,我说

var collection = new Backbone.Collection.exted({ 
  model: model,
  url: '/api/friends'
});
collection.fetch();

好的,在服务器上(nodejs + express)我可以用 app.get('/api/friends', friends.get);

在«friends»模块中,我有«get»功能。它连接到数据库,尝试从«friends»集合中获取数据(如果集合不存在,则必须创建)。如果集合为空,函数必须初始化对 vk.com(社交网络)服务器的数据请求。

/*
 * GET friends
 */
var https = require('https'),
  Db = require('mongodb').Db,
  Server = require('mongodb').Server;

var client = new Db('data', new Server('127.0.0.1', 27017, {})),
  friends;

function getAllFriends(err, collection) {
  if (!collection.stats()) {
    https.get('https://api.vk.com/method/friends.get?access_token=' + global['access_token'], function (d) {
      var chunk = '',
        response;
      d.on('data', function (data) {
        chunk += data;
      });

      d.on('end', function () {
        response = JSON.parse(chunk).response;
        response.forEach(function (friend) {
          collection.insert(friend, function (err, docs) {
            if (err) console.log(err);
          });
        });
      }).on('error', function (e) {
        console.error(e);
      });
    });
  }

  friends = collection.find({}, {
    limit: 1000
  }).toArray(function (err, docs) {
    return docs;
  });
}

exports.get = function (req, res) {
  client.open(function (err, pClient) {
    client.collection('friends', getAllFriends);
    res.send(friends);
  });
};

但是这段代码不起作用。我不知道为什么。

/node_modules/mongodb/lib/mongodb/connection/server.js:524
        throw err;
              ^
TypeError: Cannot read property 'noReturn' of undefined
    at Cursor.nextObject.commandHandler (/node_modules/mongodb/lib/mongodb/cursor.js:623:17)
    at Db._executeQueryCommand (/node_modules/mongodb/lib/mongodb/db.js:1702:5)
    at g (events.js:192:14)
    at EventEmitter.emit (events.js:126:20)
    at Server.Base._callHandler (/node_modules/mongodb/lib/mongodb/connection/base.js:130:25)
    at Server.connect.connectionPool.on.server._serverState (/node_modules/mongodb/lib/mongodb/connection/server.js:517:20)
    at MongoReply.parseBody (/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js:127:5)
    at Server.connect.connectionPool.on.server._serverState (/node_modules/mongodb/lib/mongodb/connection/server.js:476:22)
    at EventEmitter.emit (events.js:96:17)
    at _connect (/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:175:13)

也许这段代码没有在需要时创建集合?

也许我做错了什么,所以你能给我一个很好的链接来阅读 nodejs 或 mongo 中的教程。

感谢您的建议,请原谅我的英语。

【问题讨论】:

  • 您需要了解异步函数必须与回调一起使用,您不能获取它们的返回值。例如,fetchFriends().forEach 无法工作。

标签: node.js mongodb rest


【解决方案1】:

有很多代码在这里不起作用。以此为例:

 if (!collection.stats()) {
    fetchFriends().forEach(function (friend) {
      collection.insert(friend, function (err, docs) {
        if (err) console.log(err);
      });
    });
  }

  friends = collection.find({}, {
    limit: 1000
  }).toArray(function (err, docs) {
    return docs;
  });
}

首先,您不能像使用 fetchFriends 那样做。该函数不返回任何内容,所有工作都在异步回调中完成。

其次,如果它是空的,您仍然会触发直接查找的调用,而不是等到插入结果完成。

甚至调用链的开头都被破坏了:

exports.get = function (req, res) {
  client.open(function (err, pClient) {
    client.collection('friends', getAllFriends);
    res.send(friends);
  });
};

你不能在调用client.colleciton之后再调用res.send,你需要在getAllFriends中工作完成后的回调中这样做。

在你所做的事情中普遍缺乏对异步代码的理解,我认为现在不要担心 node/mongo 教程,而是先玩 node,然后看看异步库和承诺,直到你对异步感到满意。

【讨论】:

    【解决方案2】:

    我不知道这段代码应该做什么。

    • 减少正在调试的代码量;
    • 清楚地指出什么没有给你你所期望的;
    • 使用console.log

    你可能首先会发现:

    exports.get = function (req, res) {
      client.open(function (err, pClient) {
        client.collection('friends', getAllFriends);
        res.send(friends);
      });
    };
    

    不起作用,因为变量“friends”不是您所期望的。

    【讨论】:

    猜你喜欢
    • 2014-07-16
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 2019-11-27
    • 2019-01-13
    • 2023-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多