简体   繁体   中英

DocumentDB: Access document by database name, collection ID and document ID in Node.js

I'm making my first application using DocumentDB. I'm developing an API for it in Node.js. As others have noted, the DocumentDB APIs are very confusing and appear to require convoluted code to achieve simple things.

My API will allow me to access data in the database with a URL of the form http://<host>/data/<databaseName>/<collectionID>/<documentId>/<pathToData> . If <pathToData> is empty, then I will get the whole document as a JSON object.

I want a function with the signature GetDocument(databaseName,collectionID,documentId,callback) , where callback is a function that takes the particular document as a JavaScript object. What implementation of GetFunction achieves my goal?

The DoQmentDB library makes for a trivial solution.

// dbClient: require('documentdb').DocumentClient; new DocumentClient(host,options); 
// callback: function(document)
function getDocument(dbClient,databaseId,collectionId,documentId,callback) {
    var DoQmentDB  = require('doqmentdb');
    var db = new DoQmentDB(dbClient,databaseId);
    var collection = db.use(collectionId);
    collection.findById(documentId).then(callback);
}

You first need your method to initialize a documentclient object with the database and collection parameters, which you do with the readorcreatedatabase and readorcreatecollection methods, as showcased in the documentation. Once you have that object initialized, you can query specific objects by document id or by a custom query string.

Ideally, you should cache those database and collection objects upon first request, so that you don't hit the db asking for the same information upon every single request you issue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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