js中的DocumentDB连接:“require未定义”

时间:2016-12-07 22:32:09

标签: javascript cordova azure-cosmosdb

我已经能够创建数据库并进行查询。使用Microsoft的使用node.js进行查询的教程,我已经能够使用以下代码完成此任务:

// Simple Query
    "use strict";
var documentClient = require("documentdb").DocumentClient;
var config = require("./config");
var url = require('url');

// use the previously saved config.endpoint and config.primaryKey to create a new DocumentClient
var client = new documentClient(config.endpoint, { "masterKey": config.primaryKey });

// These urls are how the DocumentDB client will find the right database and collection.
var HttpStatusCodes = { NOTFOUND: 404 };
var databaseUrl = `dbs/${config.database.id}`;
var collectionUrl = `${databaseUrl}/colls/${config.collection.id}`;

// Query JSON document collection
function queryCollection() {
    console.log(`Querying collection through index:\n${config.collection.id}`);

    return new Promise((resolve, reject) => {
        client.queryDocuments(
            collectionUrl,
            'SELECT VALUE gd.NFL FROM GamblersDenDB gd WHERE gd.id = "SanDiego"'
        ).toArray((err, results) => {
            if (err) reject(err)
            else {
                for (var queryResult of results) {
                    let resultString = JSON.stringify(queryResult);
                    console.log(`\tQuery returned ${resultString}`);
                }
                console.log();
                resolve(results);
            }
        });
    });
};

queryCollection() 

在命令提示符下运行该js文件有效!它导致输出:

C:\Users\kenv\Desktop\DocDB Test>node SimpleQuery.js
Querying collection through index:
GamblersDenColl
        Query returned {"ID":"SDC","name":"Chargers"}

大。所以现在我已将我的代码转移到我的项目文件夹,并尝试使用

在应用程序中运行
taco run android --device

当我拉起控制台时,第一个突出的错误是

Uncaught ReferenceError: require is not defined(…)

它指向代码中的行var documentClient = require("documentdb").DocumentClient;

这是我的完整js文件代码,它引发了错误:

(function () {
    "use strict";

    document.addEventListener( 'deviceready', onDeviceReady.bind( this ), false );

    function onDeviceReady() {
        navigator.splashscreen.hide();
        console.log("Cordova is READY!");

        // Handle the Cordova pause and resume events
        document.addEventListener( 'pause', onPause.bind( this ), false );
        document.addEventListener( 'resume', onResume.bind( this ), false );

        $(".btnURL").on("click", function(){loadURL($(this))});
        function loadURL(theObj) {
            cordova.InAppBrowser.open(theObj.data("url"), "_blank", "location=yes");
        }


        //********* jQuery VARIABLES ***************//
        var $elBtnSaveName= $("#btnSaveName"),
            $elShowClients= $("#btnShowClients"),
            $elDivShow= $("#divShow"),
            $elFormClient= $("#formClient");

        //********** EVENT HANDLERS *****************//
        $elShowClients.on("click", queryCollection);

        //********************* DOCUMENT DB SECTION *********************************************************/
        var documentClient = require("documentdb").DocumentClient;
        var config = require("./config");
        var url = require('url');

        // use the previously saved config.endpoint and config.primaryKey to create a new DocumentClient
        var client = new documentClient(config.endpoint, { "masterKey": config.primaryKey });

        // These urls are how the DocumentDB client will find the right database and collection.
        var HttpStatusCodes = { NOTFOUND: 404 };
        var databaseUrl = `dbs/${config.database.id}`;
        var collectionUrl = `${databaseUrl}/colls/${config.collection.id}`;

        // Query JSON document collection
        function queryCollection() {
            console.log(`Querying collection through index:\n${config.collection.id}`);

            return new Promise((resolve, reject) => {
                client.queryDocuments(
                    collectionUrl,
                    'SELECT VALUE gd.NFL FROM GamblersDenDB gd WHERE gd.id = "SanDiego"'
                ).toArray((err, results) => {
                    if (err) reject(err)
                    else {
                        for (var queryResult of results) {
                            let resultString = JSON.stringify(queryResult);
                            console.log(`\tQuery returned ${resultString}`);
                        }
                        console.log();
                        resolve(results);
                        fnShowClientsTable(result.rows);
                    }
                });
            });
        };

        function fnShowClientsTable(data){
            var str = "<p><table id='tableResults'";
                str += "<tr><th>ID</th><th>Name</th><th class='thEmpty'>&nbsp;</th></tr>" //added class to <th> for formatting
                    for(var i = 0; i < data.length; i++) { // For X number of times worth of data...
                        str += "<tr><td>"  + data[i].doc.ID +  
                               "</td><td>" + data[i].doc.name + 
                               "</td><td class='btnPencil'>&#x270e;</td></tr>";
                    }
                str += "</table></p>";  // END table
                $elDivShow.html(str);   //Show string as HTML on screen

        } // END fnShowClientsTable

        //************************* END DOCUMENT DB SECTION ******************************************************/

    }; // END onDeviceReady()

    function onPause() {
        // TODO: This application has been suspended. Save application state here.
    };

    function onResume() {
        // TODO: This application has been reactivated. Restore application state here.
    };
} )();

我意识到我的另一个功能是将其推送到字符串以便在HTML中显示可能是错误的(我肯定会有另一篇文章关于那个:))但是现在我正试图确定我怎么能过去第一个错误。

0 个答案:

没有答案