Mongoose自动递增多个模型初始化连接

时间:2018-01-09 16:11:32

标签: mongodb mongoose

我正在使用插件
mongoose-auto-increment 它工作正常。

在描述中我们必须像这样使用它



var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    autoIncrement = require('mongoose-auto-increment');
 
var connection = mongoose.createConnection("mongodb://localhost/myDatabase");
 
autoIncrement.initialize(connection);
 
var bookSchema = new Schema({
    author: { type: Schema.Types.ObjectId, ref: 'Author' },
    title: String,
    genre: String,
    publishDate: Date
});
 
bookSchema.plugin(autoIncrement.plugin, 'Book');
var Book = connection.model('Book', bookSchema);




我有多个模型需要自动增加字段

我是否必须在每个模型中初始化以下行

var connection = mongoose.createConnection("mongodb://localhost/myDatabase");

在每个模型文件中(我需要增量函数)?

1 个答案:

答案 0 :(得分:0)

我分享了我自己实施的解决方案

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var autoIncrement = require('mongoose-auto-increment');
var connection = mongoose.createConnection("mongodb://localhost/mydatabase");
autoIncrement.initialize(mongoose.connection);

exports.mongoose = mongoose;
exports.Schema = Schema;
exports.autoIncrement = autoIncrement;

和架构文件

var mong = require('./db');
var Schema = mong.mongoose.Schema;
var autoIncrement = mong.autoIncrement;
 
var bookSchema = new Schema({
    author: { type: Schema.Types.ObjectId, ref: 'Author' },
    title: String,
    genre: String,
    publishDate: Date
});
 
bookSchema.plugin(autoIncrement.plugin, 'Book');
module.exports = mong.mongoose.model('Book', bookSchema);