当前位置:  开发笔记 > 编程语言 > 正文

错误:mongoose-auto-increment尚未初始化

如何解决《错误:mongoose-auto-increment尚未初始化》经验,为你挑选了1个好方法。

我正在创建一个mongoose模式如下:

var adminSchema = new mongoose.Schema({
email:{type:String,unique:true,required:true},
passwordHash:{type:String},
isActivated:{type:Boolean},
admin_id:{type:Number,unique:true}
});

adminSchema.plugin(autoIncrement.plugin(),{model:'adminSchema',
field:'admin_id',
startAt:1,
incrementBy:1});

当我尝试运行该应用程序时,我收到一个错误说:

 if (!counterSchema || !IdentityCounter) throw new Error("mongoose-auto-increment has not been initialized");
                                      ^

Error: mongoose-auto-increment has not been initialized
at Object.exports.plugin (/Users/kumar/WebstormProjects/code-master/node_modules/mongoose-auto-increment/index.js:36:49)
at Object. (/Users/kumar/WebstormProjects/code-master/models/admin.js:22:34)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Module.require (module.js:366:17)
at require (module.js:385:17)
at Object.global.App.require (/Users/kumar/WebstormProjects/code-master/app.js:23:16)
at Object.global.App.model (/Users/kumar/WebstormProjects/code-master/app.js:32:21)
at init (/Users/kumar/WebstormProjects/code-master/app/initializers/passport.js:6:15)
at Object. (/Users/kumar/WebstormProjects/code-master/app.js:66:44)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)

我正在尝试这样的连接:

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

 function connect(connectionString){
mongoose.connect(connectionString);

var db = mongoose.connection;
autoIncrement.initialize(db);
db.on('error',console.error.bind(console,"Connection error"));
db.once('open',function callback(){
   console.log("Connection established via :"+connectionString);
});

}

这是我在mongoose-aut-increment上的第一次拍摄,因此我无法弄清楚我的错误,有人可以帮忙吗?



1> Garbage..:

这发生在我身上,因为当执行此代码时,mongoose没有完全连接到数据库.我将代码更改为以下内容并且有效.

var mongoose = require('mongoose');

var adminSchema = new mongoose.Schema({
  email: {type: String, unique: true, required: true},
  passwordHash: {type: String},
  isActivated: {type: Boolean},
  admin_id: {type: Number, default: 0, unique: true}
});

module.exports = mongoose.model('adminSchema', adminSchema);
autoIncrement.initialize(mongoose.connection); // This is important. You can remove initialization in different file
adminSchema.plugin(autoIncrement.plugin, {
  model: 'adminSchema',
  field: 'admin_id',
  startAt: 1,
  incrementBy: 1
});

推荐阅读
wangtao
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有