-1

クライアントでバックボーンアプリケーションを使用し、サーバー側でnodejs+mongodbを使用してRESTAPIを作成するにはどうすればよいですか。

私は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でチュートリアルを読むための良いリンクを教えてください。

あなたのアドバイスに感謝し、私の英語をごめんなさい。

4

2 に答える 2

2

ここでは機能しないコードがたくさんあります。これを例に取ってください:

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

res.send呼び出した後に呼び出すことはできませんclient.colleciton。getAllFriendsで作業が完了した後、コールバックでこれを行う必要があります。

あなたがしていることを通して非同期コードの一般的な理解が不足しています、私は今のところノード/モンゴのチュートリアルについて心配する必要はないと思います、むしろ最初にノードで遊んで、あなたがするまで非同期ライブラリと約束を見てください非同期で快適。

于 2013-02-28T14:46:28.890 に答える
1

このコードが何をするのかわかりません。

  • デバッグするコードの量を減らします。
  • あなたが期待しているものを提供していないものを明確に識別します。
  • console.log を使用する

あなたはおそらく最初にそれを見つけるでしょう:

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

変数「friends」が期待どおりではないため、機能しません。

于 2013-02-28T15:02:00.090 に答える