猫鼬中的自动增量ID [英] auto increment ids in mongoose

查看:76
本文介绍了猫鼬中的自动增量ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在猫鼬中拥有自动递增的ID?我希望我的ID以1、2、3、4开头,而不是mongodb为您创建的怪异ID号吗?

How do I have autoincrement ids in mongoose? I want my ids to start like 1, 2, 3, 4, not the weird id numbers mongodb creates for you?

这是我的模式:

var PortfolioSchema = mongoose.Schema({
    url: String,
    createTime: { type: Date, default: Date.now },
    updateTime: { type: Date, default: Date.now },
    user: {type: Schema.Types.ObjectId, ref: 'User'}
});

推荐答案

使用mongoose-auto-increment: https://github.com/codetunnel/mongoose-auto-increment

Use mongoose-auto-increment: https://github.com/codetunnel/mongoose-auto-increment

var mongoose = require('mongoose');
var autoIncrement = require('mongoose-auto-increment');
var connection = ....;
autoIncrement.initialize(connection);

var PortfolioSchema = new mongoose.Schema({
    url: String,
    createTime: { type: Date, default: Date.now },
    updateTime: { type: Date, default: Date.now },
    user: {type: Schema.Types.ObjectId, ref: 'User'}
});

//Auto-increment
PortfolioSchema.plugin(autoIncrement.plugin, { model: 'Portfolio' });

module.exports = mongoose.model('Portfolio', PortfolioSchema);

或者,如果您希望使用其他字段而不是覆盖_id,只需添加该字段并在自动增量初始化中将其列出:

Or if you prefer to use an additional field instead of overriding _id, just add the field and list it in the auto-increment initialization:

var PortfolioSchema = new mongoose.Schema({
    portfolioId: {type: Number, required: true},
    url: String,
    createTime: { type: Date, default: Date.now },
    updateTime: { type: Date, default: Date.now },
    user: {type: Schema.Types.ObjectId, ref: 'User'}
});

//Auto-increment
PortfolioSchema.plugin(autoIncrement.plugin, { model: 'Portfolio', field: 'portfolioId' });

这篇关于猫鼬中的自动增量ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆