自动递增序列字段错误 - MongoDB,Mongoose

时间:2016-03-10 11:34:40

标签: javascript node.js mongodb mongoose

我按照这个SO问题在mongoose中生成一个自动增量序列字段。

但是在实施和运行代码我得到以下错误:

TypeError: Cannot read property 'seq' of null

下面是我的代码:

Counter.js文件

// app/models/counter.js
// load the things we need
var mongoose = require('mongoose');

// define the schema for our user model
var counterSchema = mongoose.Schema({
   _id: {type: String, required: true},
   seq: {type: Number, default: 0}
});

// methods ======================

// create the model for users and expose it to our app
 module.exports = mongoose.model('Counter', counterSchema);

SupportTicket.js文件

var Counter = require('../models/counter');
var ticketSchema = mongoose.Schema({

    issue: String,
    ticketNo: Number,
    dateCreated : { type: Date, default: Date.now }
 });

ticketSchema.pre('save', function(next) {
    var doc = this;
    Counter.findByIdAndUpdate({_id: 'entityId'}, {$inc: { seq: 1}}, function(error, counter)   {
     if(error)
        return next(error);
    doc.ticketNo = counter.seq;
    next();
  });
});

我无法弄清楚为什么我得到“无法读取属性'seq'为null” 有什么建议吗?

1 个答案:

答案 0 :(得分:0)

counter.findByIdAndUpdate({_id: 'url_count'}, 
{$inc: {seq: 1} }, 
{upsert: true , new: true},  
function(error, counter)

添加此行。它将正常工作。

{upsert: true , new: true}