2014-01-16 39 views
0

我試圖將monogdb查詢的結果返回到一個web應用程序。最簡單的最初一個剛剛返回全額徵收,你會看到它在MongoDB的控制檯從項目中的Web服務調用訪問數據庫:通過webservice c的mongodb集合#

> db.usercollection.find() 
{ "_id" : ObjectId("52d2f2b3c60804b25bc5d2ca"), "username" : "testuser1", "email 
    " : "[email protected]" } 
{ "_id" : ObjectId("52d2f2f9c60804b25bc5d2cb"), "username" : "testuser2", "email 
    " : "[email protected]" } 
{ "_id" : ObjectId("52d2f2f9c60804b25bc5d2cc"), "username" : "testuser3", "email 
    " : "[email protected]" } 
> 

我想獲得生成的JSON到一個ExtJS格。我想辦法,看看它的工作原理,但第一個問題實際上是如何返回上面的結果:

<WebMethod()> _ 
<ScriptMethod(UseHttpGet:=True, ResponseFormat:=ResponseFormat.Json)> _ 
Public Function getDBData() As String 

    Dim response As String = String.Empty 

    mongo.Connect() 
    Dim db = mongo.GetDatabase("nodetest1") 

    Using mongo.RequestStart(db) 
     Dim collection = db.GetCollection(Of BsonDocument)("usercollection").FindAll() 

     response = collection.Collection.ToString 

     Return response 
    End Using 

我沒有看到的結果,我想在這裏:

var newStore = Ext.create('Ext.data.JsonStore', { 
    model: 'User', 
    proxy: { 
     type: 'ajax', 
     url: 'http://localhost:52856/WCFService/WebService1.asmx/getDBData', 
     reader: { 
      type: 'json', 
      root: 'd', 
      idProperty: '_id', 
      successProperty: 'success' 
     }, 
     success: function (response, options) { 
      var s = response.responseText; 
      Ext.MessageBox.alert(s, 'LA LA LA'); 
      newStore.loadData(s); 
     }, 
     failure: function (response, options) { 
      Ext.MessageBox.alert('FAILED AGAIN', 'SUCKS'); 
     } 
    } 
}); 

我嘗試添加根如下:

 response = "{""d"":" + response + "}" 

     Return response 

第二種替代方案是直接調用從node.js的服務,但沒有顯示出如何設置的結果也:

Ext.Ajax.request({ 
    url: 'http://localhost:3000/userlist', 
    method: 'GET', 
    success: function (response, options) { 
     var s = response.responseText; 
     Ext.MessageBox.alert(s, 'WOO WOO'); 
     myStore.loadData(s); 
    }, 
    failure: function (response, options) { 
     Ext.MessageBox.alert('FAILED MOFO', 'Unable to GET'); 
    } 
}); 

這是我得到的結果:

nodetest1.usercollection 

查看:用戶列表

extends layout 

block content 
h1. 
    User List 
u1 
each user, i in userlist 
    li 
     a(href="mailto:#{user.email}")= user.username 

缺省路由

exports.index = function(db) { 
return function(req, res) { 
var collection = db.get('usercollection'); 
collection.find({},{}, function(e,docs){ 
     res.render('userlist', { 
      "userlist" : docs 
     }); 
}); 
}; 

};

我在這裏的方式或有人可以看到我做錯了什麼。

回答

2

致電FindAll返回MongoCursor

一個快速的方法將其轉換成一個JSON格式是:

Return collection.ToArray().ToJSON() 

你可以通過每個結果循環使用這樣的技術:

For Each document in collection 
    ' do something with each document 
Next document 

根據結果的大小,您可能會發現返回響應會使用大量的服務器內存,並需要大量時間用JavaScript進行傳輸和處理。

此外,對於生產代碼,我建議只連接到MongoDB一次。連接是線程安全的並且可重用(並使用連接池來支持多個客戶端)。打開和關閉連接是「昂貴的」。