- Third parameter added to useLocalMongo,
options
, - You can now control the generation of
timestamps
andid
of a document. - Bug fixes
npm install --save localstorage-mongo
Then import it in your react file like:
import useLocalMongo from 'localstorage-mongo'
// Schema-less model
const Book = useLocalMongo('books')
// Providing schema and options
const userSchema = {
name: { type: 'String', required: true },
age: { type: 'Number', default: 18 },
hobbies: { type: 'Array', default: ['football', 'cricket'] },
}
const userOptions = {
timestamps: true // allows the creation of createdAt and updatedAt fields.
}
const User = useLocalMongo('users', schema, options)
NOTE: Types must be provided as a string, unlike in mongoose.
You can make a property required or set a default value for it. There are a few other validation options:
type
: the type of the property's value, must be provided as a string such as "Boolean"enum
: can be provided for a property with type string, it checks whether the value is in the array provided. Example:{ status: { enum: ['pending', 'delivered'] } }
unique
: can be provided for a property to ensure that it stays unique through out the store.required
: to ensure that the value must be provided for a property.default
: this is a fallback value for the property that isn't required, and isn't provided.
timestamps
: set tofalse
as default, is a boolean which must be set to true if you want the createdAt and updatedAt properties.id
: is a boolean which must be set tofalse
if you don't want to generate ids.
User.docs // [{...}, {...}]
User.create({ name: 'maf' })
.then(user => console.log(user))
.catch(err => console.error(err))
const _id = 'bca4ed840c2c2bf674eccc3c'
User.findByIdAndUpdate(_id, (user) => {
return {
...user, // don't spread the previous document if you wanna replace instead
name: 'New Name'
}
})
.then(user => console.log(user))
.catch(err => console.log(err))
You can access the document in the callback function, and return the updated document in the callback.
Don't spread the previous document, inside callback, if you want to replace it instead of updating, validations would still apply.
User.findByIdAndDelete(_id)
.then(() => console.log('Deleted'))
.catch(err => console.log('Could not delete the document'))
MIT © mafgit