Product
Introducing SSO
Streamline your login process and enhance security by enabling Single Sign-On (SSO) on the Socket platform, now available for all customers on the Enterprise plan, supporting 20+ identity providers.
@dashersw/mongoose-id-autoinc
Advanced tools
Readme
mongoose的一个plugin,用来解决使用mongoose时mongodb的_id自增问题,摆脱一堆对人类不友好的_id字段。 自增字段名可以自定义。
##原理参照
MongoDB的官方文档
Create an Auto-Incrementing Sequence Field
采用的是方法一,在数据库中新建了一个counter计数的collection,记录每个model的大id,然后在save时赋值。 使用findAndModify实现递增,由于$inc是原子操作,所以不用担心并发。
通过npm
npm install mongoose-id-autoinc
model
- Mongoose model的名字,必须的选项field
- 自增字段的名,默认为_idstart
- 自增的初始值,默认1step
- 自增的步长,默认1例子代码:
$ node examples/example.js
1.在项目里require mongoose以及插件
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
db = mongoose.createConnection('127.0.0.1', 'yourDatabaseName'),
autoinc = require('mongoose-id-autoinc');
2.初始化插件,然后定义你自己的表结构,在和插件关联上
autoinc.init(db);
//可以指定counter名称,init(db,countername)
var UserSchema = new Schema({
name: String,
email: String
});
UserSchema.plugin(autoinc.plugin, { model: 'User' });
3.然后就可以创建自己的model,它的_id就会自增(1,2,3...)
var User = db.model('User', UserSchema);
4.可选字段
UserSchema.plugin(autoinc.plugin, { model: 'User', field: 'seqnumber', start: 100, step: 10 });
FAQs
Creating of auto increment id fields
The npm package @dashersw/mongoose-id-autoinc receives a total of 6 weekly downloads. As such, @dashersw/mongoose-id-autoinc popularity was classified as not popular.
We found that @dashersw/mongoose-id-autoinc demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Streamline your login process and enhance security by enabling Single Sign-On (SSO) on the Socket platform, now available for all customers on the Enterprise plan, supporting 20+ identity providers.
Security News
Tea.xyz, a crypto project aimed at rewarding open source contributions, is once again facing backlash due to an influx of spam packages flooding public package registries.
Security News
As cyber threats become more autonomous, AI-powered defenses are crucial for businesses to stay ahead of attackers who can exploit software vulnerabilities at scale.