我想使用Azure在DocumentDB中创建一个集合。我有一个代码,但在执行时会抛出一个错误,说明"无法读取属性' _self'未定义"。 以下是我的代码,任何人都可以查看我的代码并帮助我。
app.js
var DocumentClient = require("documentdb").DocumentClient;
//the URI value from the DocumentDB Keys blade on http://portal.azure.com
var endpoint ="https://somedbname.documents.azure.com:443/";
//the PRIMARY KEY value from the DocumentDB Keys blade on
http://portal.azure.com
var authkey =
"SomeAuthKey==";
var client = new DocumentClient(endpoint,{"masterkey": authkey});
var databaseDefinition = {"id": "documentdb1"};
var collectionDefinition = {"id": "table1"};
var documentDefinition = {
"id": "pgogula",
"stuff": "Hello World",
"bibbidi": {
"bobbidi": "boo"
}
};
client.createDatabase(databaseDefinition, function(err,database){
client.createCollection(database._self,collectionDefinition,
function(err,collection){
client.createDocument(collection._self, documentDefinition,
function(err,document){
client.queryDocuments(collection._self,"SELCT * FROM docs d WHERE
d.bibbidi.bobbidi='boo'").toArray(function(err, results){
console.log("Query Results:");
console.log(results);
});
});
});
});
错误:
D:\Node.js\azure\nodetest>node app.js
D:\Node.js\azure\nodetest\app.js:20
client.createCollection(database._self,collectionDefinition, function(err,coll
^
TypeError: Cannot read property '_self' of undefined
at D:\Node.js\azure\nodetest\app.js:20:33
at IncomingMessage.<anonymous> (D:\Node.js\azure\nodetest\node_modules\docum
entdb\lib\request.js:49:14)
at IncomingMessage.emit (events.js:129:20)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)
答案 0 :(得分:4)
以下是一些提示:
查看您获得的例外情况:
client.createCollection(database._self,collectionDefinition, function(err,coll
^
TypeError: Cannot read property '_self' of undefined
database
未定义,因为您收到传入回调的错误。看起来你收到的错误信息是:
{ code: 401, body: '{"code":"Unauthorized","message":"Required Header authorization is miss ing. Ensure a valid Authorization token is passed.\\r\\nActivityId: a98d9f51-982 a-450d-8bc1-f1a0ce5c7eb2"}' }
错误消息表明客户端未能使用您的authkey对数据库请求进行签名。查看代码,客户端需要masterKey
属性(注意驼峰式大小写)而不是masterkey
。替换以下字符串将修复您的代码:
var client = new DocumentClient(endpoint,{"masterkey": authkey});
使用:
var client = new DocumentClient(endpoint,{"masterKey": authkey});
公开发布您的身份验证密钥很危险 - 现在任何人都可以访问您的数据库。我强烈建议重新生成钥匙;从stackoverflow中删除它是不够的。
您在以下文档查询中有拼写错误,这将导致查询失败。请替换:
client.queryDocuments(collection._self,"SELCT * FROM docs d WHERE d.bibbidi.bobbidi='boo'")
使用:
client.queryDocuments(collection._self,"SELECT * FROM docs d WHERE d.bibbidi.bobbidi='boo'")
这应该让您的代码正常工作;或至少它在我的电脑上完成:)