Database API
The database API lets you execute queries and manipulate data in the built in NoSQL datastore.
API quick overview
- Datastore.open()
- insertOne(collection, document)
- getOne(collection, ID)
- findOne(collection, ID)
- find(collection, options)
- getMany(collection, options)
- toArray(collection, options)
- updateOne(collection, ID, document, options)
- updateMany(collection, document, options)
- replaceOne(collection, ID, document, options)
- replaceMany(collection, document, options)
- removeOne(collection, ID)
- removeMany(collection, options)
Datastore.open()
Datastore.open() opens a connection to a datastore in the active project space.
import {Datastore} from 'codehooks-js'
async function myfunc() {
const conn = await Datastore.open();
// use conn to call API functions
...
}
Returns Promise / Datastore connection
insertOne(collection, document)
Insert a new data object into a collection in a datastore.
Parameters
- collection: collection name
- document: JSON document or array of JSON documents
Returns Promise with the new JSON document and an unique _id
value.
Code example
import {app, Datastore} from 'codehooks-js'
async function createSale(req, res) {
const conn = await Datastore.open();
const doc = await conn.insertOne('sales', req.body);
// return new document to client
res.status(201).json(doc);
}
// Serverless route hook
app.post('/sales', createSale);
export default app.init(); // Bind functions to the serverless runtime
Example input and result
POST
https://myproject-ff00.api.codehooks.io/dev/sales
Example input:
{
"Region": "North America",
"Item Type": "Cereal",
"Volume": 200
}
getOne(collection, ID)
Get one data object by ID from a collection in a datastore.
Parameters
- collection: name of collection
- ID: the
_id
value, or Array of_id
values
Returns Promise with json document
Code example
import {app, Datastore} from 'codehooks-js'
async function getOne(req, res) {
const conn = await Datastore.open();
const id = {req.params};
const data = await conn.getOne('customer', id);
res.json(data)
}
// Serverless route hook
app.get('/cust/:id', getOne);
export default app.init(); // Bind functions to the serverless runtime
Example input and result
GET
https://myproject-ff00.api.codehooks.io/dev/cust/640f60f2b4fdc00015c42811
Example output:
{
"name": "Acme Inc.",
_id: "640f60f2b4fdc00015c42811"
}
findOne(collection, ID)
Alias for getOne
find(collection, options)
Alias for getMany
getMany(collection, options)
Stream multiple data objects from a collection in a datastore.
Data are sorted naturally by the index for the collection, default index is by _id
which will stream data in chronological order.
Parameters
- collection: collection name (mandatory)
- options (optional settings for indexes and filtering)
- filter : mongoDB query object. e.g.
{name: "Jane"}
(Read query language docs) - sort: mongoDB sort object. E.g. sort by name ascending
{"name": 1}
- useIndex: indexed field name
- Indexes are created with CLI, e.g.
coho createindex -c sales -i Region
- Indexes are created with CLI, e.g.
- startIndex: jump into the index
- endIndex: where to end in the index
- limit: how many items to return
- hints: include or omit fields
- Include fields example:
{$fields: {name: 1, address: 1}}
- Omit fields example:
{$fields: {name: 0, _id_: 0}}
- Include fields example:
- offset: how many items to skip before returning any
- reverse: reverese scan of index, i.e. descending sort
- filter : mongoDB query object. e.g.
Returns a JSON array data stream.
Simple code example
import {app, Datastore} from 'codehooks-js'
async function getSales(req, res) {
const conn = await Datastore.open();
conn.getMany('sales').json(res);
}
// Serverless route hook
app.get('/sales', getSales);
export default app.init(); // Bind functions to the serverless runtime
Example input and result
GET
https://myproject-ff00.api.codehooks.io/dev/sales
Example output:
[
{
"Region": "France",
"Item Type": "Veal",
"Volume": 130,
"Unit Price": 2005.7,
"Unit Cost": 11s7.11,
"_id": "640f60e2b4fdc00015c4280f"
},
{
"Region": "Germany",
"Item Type": "Haxe",
"Volume": 30,
"Unit Price": 30.4,
"Unit Cost": 32.43,
"_id": "640f60e2b4fdc00015c4282f"
}
]
Advanced code example
import {app, Datastore} from 'codehooks-js'
async function getSales(req, res) {
const conn = await Datastore.open();
const options = {
useIndex: "Region",
startIndex, "North America",
limit: 1000,
hints: {$fields: {hidden: 0, _id: 0}},
filter: {"Volume": {$gt: req.params.vol}}
}
conn.getMany('sales', options).json(res);
}
// Serverless route hook
app.get('/sales/:vol', getSales);
export default app.init(); // Bind functions to the serverless runtime
Example input and result
GET
https://myproject-ff00.api.codehooks.io/dev/sales/1000
Example output:
[
{
"Region": "North America",
"Item Type": "Cereal",
"Volume": 1304,
"Unit Price": 205.7,
"Unit Cost": 117.11
},
{
"Region": "North America",
"Item Type": "Cereal",
"Volume": 1306,
"Unit Price": 10.3,
"Unit Cost": 3.3
}
]
Streaming data code example
With the steaming API you're in full control over how to deliver data back to a client.
In this example the content-type
is set first, next the code is using forEach
to iterate the stream to output one line of data per database object.
import {app, Datastore} from 'codehooks-js'
async function getSales(req, res) {
res.set('content-type', 'text/plain')
const conn = await Datastore.open();
let count = 0;
const cursor = conn.getMany('sales', {filter: "Item Type": "Cereal"})
await cursor.forEach((item) => {
// use the response.write to stream data back to client
res.write(`Item ${count++} has volume ${item.Volume}\n`)
})
res.end()
}
// Serverless route hook
app.get('/sales', getSales);
export default app.init(); // Bind functions to the serverless runtime
Output from the streaming data code example:
Item 0 has volume 1304
Item 1 has volume 1306
...
toArray(collection, options)
Utility function to return multiple data objects as an array of objects from the getMany API call.
Simple code example
import {app, Datastore} from 'codehooks-js'
async function getSales(req, res) {
const conn = await Datastore.open();
const query = {"product": "foo"};
const array = await conn.getMany('sales', {filter: query}).toArray();
// return json array
res.json(array);
}
// Serverless route hook
app.get('/sales', getSales);
export default app.init(); // Bind functions to the serverless runtime
updateOne(collection, ID, document, options)
Update one data object by ID in a datastore collection. Input document is patched with the matched database object.
Parameters
- collection: name of collection
- ID: the
_id
value - document: new json document to update or manipulate
- options: (optional settings)
- upsert: Create a new document if ID does not exist by
{upsert: true}
- upsert: Create a new document if ID does not exist by
Returns Promise with updated json document
Code example
import {app, Datastore} from 'codehooks-js'
async function myFunc(req, res) {
const conn = await Datastore.open();
const data = await conn.updateOne('customer', req.params.id, req.body);
res.json(data);
}
// Serverless route hook
app.put('/cust/:id', myFunc);
export default app.init(); // Bind functions to the serverless runtime
Example input and result
POST
https://myproject-ff00.api.codehooks.io/dev/cust/640f60f2b4fdc00015c42811
Example input:
{
"name": "Acme Inc.",
"sales": 42
}
updateMany(collection, document, options)
Update multiple data objects in a datastore collection. Input document is patched with the matched database objects.
Parameters
- collection: name of collection
- document: new json document to update or manipulate
- options (optional settings for indexes and filtering)
- filter: mongoDB query object (docs)
- useIndex: use field index
- startIndex: jump into the index
- endIndex: where to end in the index
Returns Promise with count of objects updated
Code example
import {app, Datastore} from 'codehooks-js'
async function myFunc(req, res) {
const conn = await Datastore.open();
const options = {
filter: {"customerStatus": "GOLD"}
}
const doc = {
$inc: {"bonus": "20"},
$set: {customerStatus: "PLATINUM"}
};
const data = await conn.updateMany('customer', doc, options);
res.json(data);
}
// Serverless route hook
app.put('/cust', myFunc);
export default app.init(); // Bind functions to the serverless runtime
Example input and result
PUT
https://myproject-ff00.api.codehooks.io/dev/cust
Example output:
[
{
"name": "Acme Inc.",
"customerStatus": "PLATINUM",
"bonus": "20",
_id: "640f60f2b4fdc00015c42811"
},
{
"name": "Colo Inc.",
"customerStatus": "PLATINUM",
"bonus": "30",
_id: "640f60f2b4fdc00015c42f00"
},
...
]
replaceOne(collection, ID, document, options)
Replace one data object by ID in a datastore collection.
Input document overwrites the matched database object, the _id
value is not overwritten.
Parameters
- collection: name of collection
- ID: the
_id
value - document: new json document to replace
- options: (optional settings)
- upsert: Create a new document if ID does not exist by
{upsert: true}
- upsert: Create a new document if ID does not exist by
Returns Promise with updated json document
Code example
import {app, Datastore} from 'codehooks-js'
async function myFunc(req, res) {
const conn = await Datastore.open();
const data = await conn.replaceOne('customer', req.params.id, req.body);
res.json(data);
}
// Serverless route hook
app.put('/cust/:id', myFunc);
export default app.init(); // Bind functions to the serverless runtime
Example input and result
POST
https://myproject-ff00.api.codehooks.io/dev/cust/640f60f2b4fdc00015c42811
Example input:
{
"name": "Acme Replacement Inc.",
"sales": 0
}
replaceMany(collection, document, options)
Replace multiple data objects in a datastore collection.
Input document overwrites the matched database objects. The _id
value is not overwritten.
Parameters
- collection: name of collection
- document: new json document to replace
- options (optional settings for indexes and filtering)
- filter: mongoDB query object (docs)
- useIndex: use field index
- startIndex: jump into the index
- endIndex: where to end in the index
Returns Promise with count of objects updated
Code example
import {app, Datastore} from 'codehooks-js'
async function myFunc(req, res) {
const conn = await Datastore.open();
const options = {
filter: {"customerStatus": "GOLD"}
}
const doc = {
"Acme": "was here"
};
const data = await conn.replaceMany('customer', doc, options);
res.json(data);
}
// Serverless route hook
app.put('/cust', myFunc);
export default app.init(); // Bind functions to the serverless runtime
Example input and result
PUT
https://myproject-ff00.api.codehooks.io/dev/cust
Example output:
[
{
"Acme": "was here"
_id: "640f60f2b4fdc00015c42811"
},
{
"Acme": "was here"
_id: "640f60f2b4fdc00015c400fe"
},
...
]
removeOne(collection, ID)
Remove one data object by ID in a datastore collection.
Parameters
- collection: name of collection
- ID: the
_id
value
Returns Promise with document ID
Code example
import {app, Datastore} from 'codehooks-js'
async function myFunc(req, res) {
const conn = await Datastore.open();
const data = await conn.removeOne('customer', req.params.id);
res.json(data);
}
// Serverless route hook
app.delete('/cust/:id', myFunc);
export default app.init(); // Bind functions to the serverless runtime
Example input and result
DELETE
https://myproject-ff00.api.codehooks.io/dev/cust/640f60f2b4fdc00015c42811
Example output:
640f60f2b4fdc00015c42811
removeMany(collection, options)
Remove multiple data objects in a datastore collection.
Parameters
- collection: name of collection
- options (optional settings for indexes and filtering)
- filter: mongoDB query object (docs)
- useIndex: use field index
- startIndex: jump into the index
- endIndex: where to end in the index
Returns Promise with count of objects deleted
Code example
import {app, Datastore} from 'codehooks-js'
async function myFunc(req, res) {
const conn = await Datastore.open();
const options = {
filter: {"customerStatus": "GOLD"}
}
const data = await conn.removeMany('customer', options);
res.json(data);
}
// Serverless route hook
app.delete('/cust', myFunc);
export default app.init(); // Bind functions to the serverless runtime
Example input and result
DELETE
https://myproject-ff00.api.codehooks.io/dev/cust
Example output:
{"count": 3}