【问题标题】:RavenDB: How to create a collection?RavenDB:如何创建一个集合?
【发布时间】:2021-07-27 15:47:29
【问题描述】:

我在 ravendb 中设置了一个免费的数据库“TestDB”,当您创建一些文档时,会有默认的 @empty 集合。但是我怎样才能创建自己的收藏呢?没有关于此的文档,也没有 API 显然可以从他们的 npm ravendb 包中执行此操作...?

这是我的代码:

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()

只要我使用@empty 集合,它就可以工作..

【问题讨论】:

标签: node.js collections crud ravendb


【解决方案1】:

您可以使用文档中的字段来设置集合。

const store = new DocumentStore(urls, database);
store.conventions.findCollectionNameForObjectLiteral = entity => 
entity["collection"];
// ...
store.initialize();

https://ravendb.net/docs/article-page/5.2/nodejs/client-api/session/storing-entities

【讨论】:

  • 你能举例说明如何使用它吗?没看懂。。
【解决方案2】:

要创建一个集合,您需要创建一个带有类实例作为参数的实体。

不仅如此,如果您传递一个类的实例,它将为您生成一个唯一的 slug,而不是长 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();
}

执行 add() 在 Users 集合中添加一个新文档。

它甚至会将集合命名为用户,尽管您创建的类是用户。

user.js:

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

module.exports {
    User
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多