v0.6.0-rc.1
HomeDocumentationWorking with data

Make room for your data.

Create, read, update and delete BSON documents with the MongoDB collection API.

Get a collection

javascript
await BsonLite.connect('myapp');
const notes = BsonLite.collection('notes');

The examples below run inside an async function after connection. Collections are created by normal MongoDB writes as needed. BsonLite.collection returns a MongoDB driver Collection, rather than a separate query language.

Create documents

javascript
const result = await notes.insertOne({
  title: 'Build something useful',
  tags: ['project', 'idea'],
  done: false,
  createdAt: new Date()
});

const id = result.insertedId;

await notes.insertMany([
  { title: 'Write the docs', done: false },
  { title: 'Try the starter', done: true }
]);

MongoDB supplies an ObjectId when you omit _id. insertOne returns a write result, not the inserted document. Choose allowed fields when accepting application input.

Read documents

javascript
const note = await notes.findOne({ _id: id });

const latest = await notes
  .find({ done: false }, { projection: { title: 1, createdAt: 1 } })
  .sort({ createdAt: -1 })
  .limit(20)
  .toArray();

const pending = await notes.countDocuments({ done: false });

Use findOne for a document or null. find returns a cursor; apply sort, limit and projection before toArray. Large collections should be paginated rather than loaded into one array.

Update and delete

javascript
await notes.updateOne(
  { _id: id },
  { $set: { done: true }, $currentDate: { updatedAt: true } }
);

await notes.deleteOne({ _id: id });
// deleteMany({}) deletes every document. Require a deliberate filter.
Validate application requests

The SDK provides database authentication and encrypted storage. Your application still decides who may read or change records. Do not pass an untrusted request body straight into a filter or update document.

Documentation for BsonLite 0.6.0-rc.1. View SDK source · Download the validated SDK