RavenDB: How to create a collection?

Viewed 283

I set up a free Database "TestDB" in ravendb and there is the default @empty collection when you create some documents. But how can I create my own collection? There is no documentation about that, and no API apparently to do this from their npm ravendb package...?

Here is my code:

import { DocumentStore } from 'ravendb'
import * as fs from 'fs'

// load certificate and prepare authentication options
const authOptions = {
    certificate: fs.readFileSync(
        'C:/Users/asdasd/Desktop/testravendb/free.asdasdasd.client.certificate.pfx'
    ),
    type: 'pfx', // or "pem"
    password: '',
}

const store = new DocumentStore(
    ['https://a.free.asdasdasd.ravendb.cloud'],
    'TestDB',
    authOptions
)
store.initialize()

console.log(store)
const session = store.openSession()
console.log(session)

let product = {
    title: 'iPhone X',
    price: 999.99,
    currency: 'USD',
    storage: 64,
    manufacturer: 'Apple',
    in_stock: true,
    last_update: new Date('2017-10-01T00:00:00'),
}
async function save() {
    await session.store(product, 'products/')
    console.log(product.id) // Products/1-A
    await session.saveChanges()
}
save()

async function getData() {
    const query = session.query({ collection: '@empty' })
    const results = await query.all()
    //let product2 = await session.load('products')
    console.log(results) // iPhone X
}

getData()

It works as long as I use the @empty collection..

2 Answers

To create a collection you need to create an entity with instance of a Class as parameter.

More than that, if you pass an intance of a class it will generate a uniqe slug for you instead of long UUID.

const { User } = require('./user.js')

const store = new DocumentStore(url, db);
store.initialize();

const add = async () => {
    const user = new User({ email@gmail.com, John, 32 })
    await session.store(user);
    await session.saveChanges();
}

execute add() to add a new document inside Users collection.

It will even name the collection as Users although the class you created is User.

user.js:

class User {
    constructor({ email, name, age}) {
        this.email = email;
        this.name= name;
        this.age= age;
    }
}

module.exports {
    User
}
Related