Skip to the content.

DocumentCollection API

The DocumentCollection API extends the Collection API with the following methods.

documentCollection.document

async documentCollection.document(documentHandle, [opts]): Document

Retrieves the document with the given documentHandle from the collection.

Arguments

If a boolean is passed instead of an options object, it will be interpreted as the graceful option.

Examples

const db = new Database();
const collection = db.collection("my-docs");

try {
  const doc = await collection.document("some-key");
  // the document exists
  assert.equal(doc._key, "some-key");
  assert.equal(doc._id, "my-docs/some-key");
} catch (err) {
  // something went wrong or
  // the document does not exist
}

// -- or --

try {
  const doc = await collection.document("my-docs/some-key");
  // the document exists
  assert.equal(doc._key, "some-key");
  assert.equal(doc._id, "my-docs/some-key");
} catch (err) {
  // something went wrong or
  // the document does not exist
}

// -- or --

const doc = await collection.document("some-key", true);
if (doc === null) {
  // the document does not exist
}

documentCollection.documentExists

async documentCollection.documentExists(documentHandle): boolean

Checks whether the document with the given documentHandle exists.

Arguments

Examples

const db = new Database();
const collection = db.collection("my-docs");

const exists = await collection.documentExists("some-key");
if (exists === false) {
  // the document does not exist
}

documentCollection.save

async documentCollection.save(data, [opts]): Object

Creates a new document with the given data and returns an object containing the document’s metadata (_id, _key and _rev attributes).

Multiple documents can be created in a single call by passing an array of objects as argument for data. The result will be an array too, of which some elements can be error objects if the documents couldn’t be saved.

Arguments

If a boolean is passed instead of an options object, it will be interpreted as the returnNew option.

For more information on the opts object, see the HTTP API documentation for working with documents.

Examples

const db = new Database();
const collection = db.collection("my-docs");
const data = { some: "data" };
const info = await collection.save(data);
assert.equal(info._id, "my-docs/" + info._key);
const doc2 = await collection.document(info);
assert.equal(doc2._id, info._id);
assert.equal(doc2._rev, info._rev);
assert.equal(doc2.some, data.some);

// -- or --

const db = new Database();
const collection = db.collection("my-docs");
const data = { some: "data" };
const opts = { returnNew: true };
const doc = await collection.save(data, opts);
assert.equal(doc1._id, "my-docs/" + doc1._key);
assert.equal(doc1.new.some, data.some);