Git Product home page Git Product logo

lodash-id's Introduction

lodash-id Build Status NPM version

lodash-id makes it easy to manipulate id-based resources with lodash or lowdb

  • getById
  • insert
  • upsert
  • updateById
  • updateWhere
  • replaceById
  • removeById
  • removeWhere
  • createId

Install

# with lodash
npm install lodash lodash-id --save

# with lowdb
npm install lowdb lodash-id --save

Note lodash-id is also compatible with underscore

API

In the API examples, we're assuming db to be:

const db = {
  posts: [
    {id: 1, body: 'one', published: false},
    {id: 2, body: 'two', published: true}
  ],
  comments: [
    {id: 1, body: 'foo', postId: 1},
    {id: 2, body: 'bar', postId: 2}
  ]
}

getById(collection, id)

Finds and returns document by id or undefined.

const post = _.getById(db.posts, 1)

insert(collection, document)

Adds document to collection, sets an id and returns created document.

const post = _.insert(db.posts, { body: 'New post' })

If the document already has an id, and it is the same as an existing document in the collection, an error is thrown.

_.insert(db.posts, { id: 1, body: 'New post' })
_.insert(db.posts, { id: 1, title: 'New title' }) // Throws an error

upsert(collection, document)

Adds document to collection, sets an id and returns created document.

const post = _.upsert(db.posts, { body: 'New post' })

If the document already has an id, it will be used to insert or replace.

_.upsert(db.posts, { id: 1, body: 'New post' })
_.upsert(db.posts, { id: 1, title: 'New title' })
_.getById(db.posts, 1) // { id: 1, title: 'New title' }

updateById(collection, id, attrs)

Finds document by id, copies properties to it and returns updated document or undefined.

const post = _.updateById(db.posts, 1, { body: 'Updated body' })

updateWhere(collection, whereAttrs, attrs)

Finds documents using _.where, updates documents and returns updated documents or an empty array.

// Publish all unpublished posts
const posts = _.updateWhere(db.posts, { published: false }, { published: true })

replaceById(collection, id, attrs)

Finds document by id, replaces properties and returns document or undefined.

const post = _.replaceById(db.posts, 1, { foo: 'bar' })

removeById(collection, id)

Removes document from collection and returns it or undefined.

const comment = _.removeById(db.comments, 1)

removeWhere(collection, whereAttrs)

Removes documents from collection using _.where and returns removed documents or an empty array.

const comments = _.removeWhere(db.comments, { postId: 1 })

id

Overwrite it if you want to use another id property.

_.id = '_id'

createId(collectionName, doc)

Called by lodash-id when a document is inserted. Overwrite it if you want to change id generation algorithm.

_.createId = (collectionName, item) => `${collectionName}-${item.prop}-${Date.now()}`

Changelog

See details changes for each version in the release notes.

License

MIT - Typicode ๐ŸŒต

lodash-id's People

Contributors

dununan avatar justcfx2u avatar lukehorvat avatar safazi avatar typicode avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lodash-id's Issues

Using json-server as basic as you can, getting "hasOwnProperty" error

During AJAX post request, the first post works but any subsequent request is failing with the following error:

TypeError: doc.hasOwnProperty is not a function

I patched the issue on my local box by editing the following file, with the following fix:
underscore-db\src\index.js:36

if (doc[self.__id()] || doc.hasOwnProperty && doc.hasOwnProperty(self.__id())) {

My node version, may have something to do with it, I'm on 7 ... Other than that I can't think of why doing standard Object key checking solves my issue.

Here is my sample data from my json-server db.json file:

{
  "users":[
    {
      "username": "acker",
      "motto": "apple",
      "id": 14
    },
    {
      "username": "test3",
      "motto": "test33",
      "id": 15
    }
  ]
}

Again, very odd, the first communication with json-server to POST data works but no further POST requests to json-server works. I know json-server is NOT your package but editing underscore-db FIXED our issue locally.

Thank you kindly for any help you maybe able to offer.

Can't use underscore-db 0.9.1 with lowdb 0.12.5 - TypeError: undefined is not a function

I was using lowdb and underscore-db without problem until now. But method where() doesn't exist anymore in newer versions of lodash, so each time I want to use a method from underscore-db, I get the following message : TypeError: undefined is not a function.
All was working fine with underscore-db 0.8.1 and lowdb 0.8.1.

Here is my previous code :
var low = require('lowdb'); low.mixin(require('underscore-db')); var db = low('db.json'); var users = db('users).removeWhere({id: 1});

I am now using :
var low = require('lowdb'); var db = low('db.json'); db._.mixin(require('underscore-db')); var users = db('users).removeWhere({id: 1});

Add upsert alias?

Hi. The insert method behaves like what is usually called upsert in most DBMS'. So could you add upsert as an alias? I think it more clearly indicates intent.

Or, alternatively, rename the current insert method to upsert, and then rewrite insert to behave like a regular DBMS insert?

Upsert updating

Is there any alternative to use upsert but updating instead of replacing?

try online is not working with chrome

when i execute

 db;
Object {posts: Array[7], comments: Array[2]}

its list the object properly
but when i execute other commands for eg., _.get(), it is giving error

_.get(db.posts,1)
TypeError: Cannot call method 'find' of undefined

Typescript support?

Hello, I couldn't find any Typescript support for this library, does it exist?

Many thanks!

Asynchronous inserts

Just a thought.
Insert-function finds the max id value and adds 1. It would be possible to obtain the same id for newly inserted id when writing multiple values asynchronously. Maybe use a lock or randomize id? Using random id (e.g. hash) would enable distributing db over multiple files and operating on each separately, thus allowing greater scalability...

_.where mentionned in documentation

Hello,
Thanks for the nice library !
I took me some time to understand what the _.where in the documentation means, as it is depreacted in 4.x and not part of lodash documentation anymore.
It would help new comers like me if it was replaced by _.find in the readme !

_replaceWhere is not available

We have updateByd and updateWhere. like wise we have replaceById but we dosen't have replaceWhere.
Can you pls supportfor replaceWhere

createId: collectionName vs collection

The documentation for createId indicates that it will be passed the collectionName and the item for which an id is being generated. It appears that it is actually passed the collection, as opposed to the collectionName. See

createId: function (collection, doc) {

example:

import low from 'lowdb'
import FileSync from 'lowdb/adapters/FileSync'
import lodashId from 'lodash-id'
import shortId from 'shortid'

const adapter = new FileSync('../../db.json')

const db = low(adapter)
db._.mixin(lodashId)
db._.createId = (collectionName) => {
  console.log(collectionName) // I expect collectionName to be 'sprockets'. Instead it is `[]`
  return `${collectionName}-${shortId.generate()}`
}

db.defaults({
  sprockets: []
}).write()

db.get('sprockets').upsert({ name: 'my sprocket' }).write()

lodash/fp

Hi,
Looks like an awesome idea.

  1. Are you planning to support lodash/fp as well?
  2. Have you looked at lodash.mixin? It allows to extend the current functionality of lodash.

Thanks

How best to merge list of new/updated objects into existing list

I receive an array of objects from an API and would like to store them. Sometimes the objects match those already in the db and other times they've been altered. This sounds like a great use of upsert.

Unfortunately, the only way I can get this to work is

users.forEach(user => db.get('users').upsert(user).write())

where users is the array of objects. Is there a better way to do this than calling write in a loop?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.