简体   繁体   English

获取Node.js和MongoDB中的收集数据

[英]get collection data in nodejs and mongodb

Tell me please, how can I create REST API using backbone application on the client and nodejs + mongodb in the server side. 请告诉我,我如何使用客户端上的主干应用程序以及服务器端的nodejs + mongodb创建REST API。

I am new in nodejs and can't understand all of the elementary things. 我是nodejs的新手,无法理解所有基本知识。

Just for example — I need to get friends collection. 仅举例来说,我需要收集朋友。 In my client app I say 在我的客户应用中,我说

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

Ok, on the server (nodejs + express) I can listen this request with app.get('/api/friends', friends.get); 好的,在服务器上(nodejs + express),我可以使用app.get('/ api / friends',friends.get);收听此请求。

in the «friends» module I have «get» function. 在“朋友”模块中,我具有“获取”功能。 It connect to database, try to get data from «friends» collection (if collection is not exist it must be create). 它连接到数据库,尝试从«friends»集合中获取数据(如果不存在集合,则必须创建它)。 If collection is empty, function must to initialize request to the vk.com (social netword) server for its data. 如果collection为空,则函数必须初始化向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);
  });
};

But this code don't work. 但是此代码不起作用。 I have no idea why. 我不知道为什么。

/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)

Maybe this code is not creating collection when it needs? 也许这段代码没有在需要时创建集合?

Maybe I do wrong anything, so can you give me a good link to read tutorial in nodejs or mongo. 也许我做错了任何事,所以您可以给我一个很好的链接,以阅读nodejs或mongo中的教程。

Thanks for your advice and sorry please for my english. 感谢您的建议,对不起,请您说我的英语。

There is a lot of code that just doesn't work here. 有很多代码在这里行不通。 Take this for example: 以这个为例:

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

For a start you can't do it like that with fetchFriends. 首先,您无法使用fetchFriends做到这一点。 That function doesn't return anything, all the work is done in async callbacks. 该函数不返回任何内容,所有工作均在异步回调中完成。

Secondly if it's empty, you're still triggering a call to find directly and not waiting till the results of your insert finish. 其次,如果它为空,则您仍在触发直接查找的调用,而不必等到插入结果完成。

Even the beginning of the call chain is broken: 甚至呼叫链的开头也坏了:

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

You can't just call res.send after calling client.colleciton , you need to do this in a callback after the work gets done in getAllFriends. 您不能只在调用client.colleciton之后调用res.send ,您需要在getAllFriends中完成工作后在回调中执行此操作。

There is a general lack of understanding of async code throughout what you're doing, I think dont worry about node/mongo tutorials for now, rather play with node more first, and have a look at the async library and promises until you're comfortable with async. 整个工作过程中普遍缺乏对异步代码的理解,我认为现在不必担心节点/ mongo教程,而是先更多地使用节点,然后看看异步库并保证直到您完成为止。适应异步。

I have no idea what this code is supposed to do. 我不知道这段代码应该做什么。

  • Reduce the amount of code you are debugging ; 减少正在调试的代码量;
  • identify clearly what is not giving you what you are expecting ; 清楚地找出不能给您期望的东西;
  • use console.log 使用console.log

you'll probably first find that : 您可能首先会发现:

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

doesn't work because the variable "friends" is not what you expect it to be. 不起作用,因为变量“ friends”不是您期望的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM