mongoose-nanoid
TypeScript icon, indicating that this package has built-in type declarations

2.1.5 • Public • Published

mongoose-nanoid

Custom Id plugin for Mongoose using nanoid

Installation

npm install --save mongoose-nanoid

Usage

const mongoose = require('mongoose');
mongoose.plugin(require('mongoose-nanoid'), size) // custom size. see nanoid for more details
--OR--
mongoose.plugin(require('mongoose-nanoid'), { length: size, alphabets: "abcd@" }) // custom size. see nanoid for more details

// or opt out for schemas
var UserSchema = new Schema({
    username: String,
    address : new Schema({
        street: String,
        City: String
    }, {_id: false})
});
UserSchema.plugin(require('mongoose-nanoid')); // default size = 12
const User = mongoose.model('User', UserSchema);

For references, use type: String

var ImageSchema = new Schema({
    user: {
      type: String,
      ref: 'User'
    },
    name: String
});

Now the _id will be generated using nanoid.

const user = new User({username: 'Prince'});
user.save(function (err) {
    console.log(user._id); // Should be generated by nanoid(size)
});

Issues

There is a possibility of duplication of id with small size, but this library makes sure that _id stays unique by first validating and then inserting.

References

nanoid : https://github.com/ai/nanoid

Package Sidebar

Install

npm i mongoose-nanoid

Weekly Downloads

36

Version

2.1.5

License

MIT

Unpacked Size

11.9 kB

Total Files

8

Last publish

Collaborators

  • adiliqbl