repl-database v1.1.2
Repl Database
Use repl's database with an easy to use collection based system.
Installation
Repl Database is only supported on node.js; you can install the package with npm install repl-database
.
Initialization
Include Repl Database at the top of the file.
const ReplDatabase = require('repl-database)
Create a new Database with the new
class constructor. Databases fetch the latest information from repl utilizing promises. As such, you will need to use await/async
when initializing a new database. You can also pass a repl database key into the constructor for multiple repl databases (defaults to process.env.REPLIT_DB_URL
)
;(async () => {
const db = await new ReplDatabase()
})()
Database Methods
You can interact with database collections with a variety of methods.
Creating Collections
You can create a new collection with db.collection(name)
. If the collection already exists, it will return it. If it does not, the database will create a new collection.
Deleting Collections
You can delete a collection with db.remove(name)
. The database will throw an error if the collection you are trying to delete does not exist. This will delete all documents within a collection.
Utility Functions
There are also a few other functions that you may want to use in the database.
db.has(name)
: checks if a collection with that particular name exists
db.get(name)
: returns a collection if it exists, throws an error if not. db.collection
uses db.get
underneath to return the correct collection.
db.list()
: returns a list of names of all of the collections
Collection Methods
Once you have retrieved a collection with db.collection
or db.get
, you can interact with the documents.
const collection = db.collection('collection')
Creating Documents
You can create a document with collection.document(json)
.
Retrieving Documents
At the moment, you can retrieve documents by accessing them directly in collection.documents
. There are also some functions similar to the database; for example you can run collection.get(id)
and collection.has(id)
.
Deleting Documents
All documents have meta information regarding their id, time of creation, and last time updated. You can delete a document with collection.remove(id)
. You can get the id of a document by retrieving it and searching for .meta._id
.
Document Methods
You can retrieve a document by looking in collection.documents
, which returns an array of documents within the collection. This array makes querying extremely versatile because you can loop, filter, map, etc.
const document = collection.documents[0] // retrieves the first document
Setting Keys
You can set a key with document.set(key, value)
. If the key starts with an underscore, it will be automatically placed under the meta information of the document.
Utility Functions
document.has
: checks if a document contains a specific property; discludes meta data.