Mongodb mongoose中的自动增量ids
我如何在mongoose中拥有自动增量ID?我希望我的id从1、2、3、4开始,而不是mongodb为您创建的奇怪id号 以下是我的模式:Mongodb mongoose中的自动增量ids,mongodb,mongoose,mongodb-query,Mongodb,Mongoose,Mongodb Query,我如何在mongoose中拥有自动增量ID?我希望我的id从1、2、3、4开始,而不是mongodb为您创建的奇怪id号 以下是我的模式: var PortfolioSchema = mongoose.Schema({ url: String, createTime: { type: Date, default: Date.now }, updateTime: { type: Date, default: Date.now }, user: {type: Sche
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'}
});
如果您希望在
\u id
中有一个递增的数值,那么基本的过程是您需要一些东西从某个存储中返回该值。一种方法是使用MongoDB本身来存储保存每个集合的\u id
值计数器的数据,该数据在手册本身的下面进行了描述
然后在创建每个新项时,使用实现的函数获取“计数器”值,并将其用作文档中的\u id
在这里重写默认行为时,mongoose要求您使用类似于\u id:Number
的内容显式地指定\u id:Number
的id和类型,并且告诉它不再自动尝试在模式上提供带有{“\u id:false}
的ObjectId
类型作为选项
下面是一个实践中的工作示例:
var async = require('async'),
mongoose = require('mongoose'),
Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/test');
var counterSchema = new Schema({
"_id": String,
"counter": { "type": Number, "default": 1 }
},{ "_id": false });
counterSchema.statics.getNewId = function(key,callback) {
return this.findByIdAndUpdate(key,
{ "$inc": { "counter": 1 } },
{ "upsert": true, "new": true },
callback
);
};
var sampleSchema = new Schema({
"_id": Number,
"name": String
},{ "_id": false });
var Counter = mongoose.model( 'Counter', counterSchema ),
ModelA = mongoose.model( 'ModelA', sampleSchema ),
ModelB = mongoose.model( 'ModelB', sampleSchema );
async.series(
[
function(callback) {
async.each([Counter,ModelA,ModelB],function(model,callback) {
model.remove({},callback);
},callback);
},
function(callback) {
async.eachSeries(
[
{ "model": "ModelA", "name": "bill" },
{ "model": "ModelB", "name": "apple" },
{ "model": "ModelA", "name": "ted" },
{ "model": "ModelB", "name": "oranage" }
],
function(item,callback) {
async.waterfall(
[
function(callback) {
Counter.getNewId(item.model,callback);
},
function(counter,callback) {
mongoose.model(item.model).findByIdAndUpdate(
counter.counter,
{ "$set": { "name": item.name } },
{ "upsert": true, "new": true },
function(err,doc) {
console.log(doc);
callback(err);
}
);
}
],
callback
);
},
callback
);
},
function(callback) {
Counter.find().exec(function(err,result) {
console.log(result);
callback(err);
});
}
],
function(err) {
if (err) throw err;
mongoose.disconnect();
}
);
为了方便起见,这在模型上实现了一个静态方法,即.getNewId()
,它只是描述性地包装了中使用的主函数。这是手册页面部分提到的.findAndModify()
的一种形式
其目的是在计数器模型集合中查找特定的“键”(实际上也是\u id
),并执行操作以“增加”该键的计数器值并返回修改过的文档。“upsert”选项也有助于这一点,因为如果请求的“key”尚未存在文档,则将创建该文档,否则该值将通过增加,因此默认值将始终为1
此处的示例显示两个计数器是独立维护的:
{ _id: 1, name: 'bill', __v: 0 }
{ _id: 1, name: 'apple', __v: 0 }
{ _id: 2, name: 'ted', __v: 0 }
{ _id: 2, name: 'oranage', __v: 0 }
[ { _id: 'ModelA', __v: 0, counter: 2 },
{ _id: 'ModelB', __v: 0, counter: 2 } ]
首先列出创建的每个文档,然后显示“counters”集合的结束状态,该集合保存请求的每个键的最后使用值
还要注意的是,这些“奇怪的数字”有一个特定的目的,即总是被保证是独一无二的,并且总是按顺序递增。请注意,这样做不需要再次访问数据库,以便安全地存储和使用递增的数字。因此,这应该很值得考虑。使用mongoose自动增量:
或者,如果您希望使用附加字段而不是覆盖\u id
,只需添加该字段并将其列在自动增量初始化中:
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' });
你能回答这个插件中发布的问题吗?这个插件自2015年以来一直没有维护过,并且回购协议已经存档。如果你搜索autoincrement
,网站上会有很多模仿的autoincrement插件。如果不是为了回调,你会更加全心全意地投票:)
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' });