npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

field-database

v1.0.16

Published

fieldDB object modeling for node.js

Downloads

10

Readme

field-database

fieldDB object modeling for node.js

Table of contents

Features

  • creation of custom classes (models) for the production of the required objects according to a pre-specified scheme
  • validation of created objects by type, need for data availability, existence of declared keys (setting when creating a model)

Installing Add the package to your project

npm i filed-database

Example

Model creation To create model that will be used in you project, use function Model provided by field-database
Export last one:

const {FieldDocumentType, Model} = require('field-database')

const schema = {
    messageText: {type: 'string', required: true},
    date: {type: 'number', required: true},
    note: {type: 'string', default: null},
    deleted: {type: 'boolean', default: false},
    likes: {type: 'object', default: []}
}

const Message = Model('message', schema)

export default Message

using TypeScript:

import {FieldDocumentType, Model} from 'field-database'


export type MessageType = FieldDocumentType & {
    messageText: string
    date: number
    note: string | null
    deleted: boolean
    likes: Array<string>
}

const schema = {
    messageText: {type: 'string', required: true},
    date: {type: 'number', required: true},
    note: {type: 'string', default: null},
    deleted: {type: 'boolean', default: false},
    likes: {type: 'object', default: []}
}


const Message = Model<MessageType>('message', schema)

export default Message

When we create a schema for the model, we may specify type, require and default parameters.
type may be:

  • 'number'
  • 'string'
  • 'boolean'
  • 'object' (arrays, objects and null)

type is required in schema, other are optional. Default value of required is false, for default is undefined


Connection to database !Before connecting to database, make you sure you have network connection!
Using express (TypeScript):

import {Express} from 'express'
const express = require('express')
import field from 'field-database'

const app: Express = express()
const PORT: number = 5000
async function start() {
    try {
        await field.connect({
            login: 'test',
            password: '111111',
            projectId: 'Project ID'
        })
        console.log('FieldDB is connected')
        app.listen(PORT, () => log.info(`Server has been started on port ${PORT}`))
    } catch (e: any) {
        console.log(`Server Error: ${e.message}`)
        process.exit(1)
    }
}

start()

Usage Continuing with the example above, using express router. Here we create new instance providing initial parameters. Method save makes corresponding records in database.

import Message from '../models/Message'
const router: IRouter = Router()

router.put('/',
    async (req, res) => {
        try {
            const {messageText} = req.body as {messageText: string}
            const message = new Message({
                messageText,
                date: Date.now()
            })
            await message.save()
            res.json({message})
        } catch (e: any) {
            log.error(e.message)
            res.status(500).json({message: 'Something went wrong'})
        }
    }
)

If we try to look what object message is, we can see:

{
    _id: 'some id',
    _creationDate: 1637876142324,
    _updatingDate: null,
    messageText: 'some message text',
    date: 1637876142324,
    note: null,
    deleted: false,
    likes: []
}

Available methods Demo version of the database make available following asynchronous methods

save save is instance method. It saves object record in database and returns a Promise without payload (void)

await message.save()

find find is static method. It returns a Promise with array payload:

// we can use this method without any parameters
// and get all objects from collection with model Message
const messages = await Message.find()
// as well as with object parameter named filter
// in this case we will get only objects according to filter value
const ownerMessages = await Message.find({ownerId: 'some id of owner'})

// filter can be compound
const ownerDeletedMessages = await Message.find({ownerId: 'some id of owner', deleted: true})

findById findById is static method. It returns a Promise with object or null payload:

// we should to provide only one parameter: id
const message = await Message.findById('some message id')
// if database find corresponding object we get object, else: null

findOne findOne is static method. It returns a Promise with object or null payload like findById

// but now we should to provide any filter instead of id
const message = await Message.findById({messageText: 'This is message'})
// in this case we get the first found object with field 'messageText' equal to 'This is message'
// or null if object not found

findByIdAndUpdate findByIdAndUpdate is also static method. It updates the object according provided filter and returns a Promise with object or null

let newMessageText = 'this is new message text'
// if we need updated object
const message = await Message.findByIdAndUpdate('some message id', {messageText: newMessageText})
// also we can ignore promise payload 
await Message.findByIdAndUpdate('some message id', {messageText: newMessageText})

findByIdAndDelete findByIdAndDelete is static. It delete the object according provided id and returns a Promise without payload (void)

await Message.findByIdAndDelete('some message id')

Errors

With model creation we should provide all required parameters without default values. Also we have to pass values of the correct types.

If we make the mistake, we get one of following error messages:

Property "messageText" is required on type Message
Property "messageLikes" does not exist on type Message
Property "messageText" should be "string" type but got "number"