Nozbe / WatermelonDB

🍉 Reactive & asynchronous database for powerful React and React Native apps ⚡️
https://watermelondb.dev
MIT License
10.62k stars 600 forks source link

Using @writer or @reader methods in WatermelonDB outside of the model class #1807

Open 1002440870 opened 4 months ago

1002440870 commented 4 months ago

class Posts extends Model { static table = 'posts'

@text('title') title: string | undefined;
@text('body') body: string | undefined;
@text('subtitle') subtitle: string | undefined;
@field('is_pinned') isPinned: boolean | undefined;

@writer async addComment(newPost: PostsType) {
    const newComment = await this.collections.get(this.table).create((posts: any) => {
        posts.title = newPost.title
        posts.subtitle = newPost.subtitle
        posts.body = newPost.body
    })
    return newComment
}

}

const insert = async () => { try { const users: Collection = RxDatabase.getCollections('posts'); // const postsModal = await users.modelClass.addComment({ // title: "New post222222", // body: "Lorem ipsum...", // subtitle: "Lorem ipsum...", // isPinned: true, // }); await users.modelClass.addComment({ title: "New post222222", body: "Lorem ipsum...", subtitle: "Lorem ipsum...", isPinned: true, }) console.log("🚀 ~ insert ~ postsModal:",) } catch (error) { console.log("🚀 ~ insert ~ error:", error) } }

jasondavis87 commented 3 months ago

I think this is what you're looking for: https://watermelondb.dev/docs/Writers#inline-writers

example copied from page

// Note: function passed to `database.write()` MUST be asynchronous
const newPost = await database.write(async => {
  const post = await database.get('posts').create(post => {
    post.title = 'New post'
    post.body = 'Lorem ipsum...'
  })
  const comment = await database.get('comments').create(comment => {
    comment.post.set(post)
    comment.author.id = someUserId
    comment.body = 'Great post!'
  })

  // Note: Value returned from the wrapped function will be returned to `database.write` caller
  return post
})