2016-08-23 157 views
1

我試着在貓鼬創建自動遞增場,但我不能創造某種原因自動增量字段

這是我app.js

var express = require('express'); 
var app = express(); 
var mongoose = require('mongoose'); 
var Artist = require('./models/artist'); 
mongoose.connect('mongodb://localhost/auto-increment'); 

app.get('/', function(req, res){ 

    Artist.create({ 
     name: "artistName", 
     fpimage: "Cover" 
    }, function(err, artist){ 
     if(err) { 
      console.log(err); 
     } else { 
      artist.save(); 
      console.log(artist); 
      res.send('Hi ') 
     } 
    }); 
}); 


// Set Port 
app.set('port', (process.env.PORT || 3000)); 
// Run Server 
app.listen(app.get('port'), function(){ 
    console.log('Server has started on Port: '+app.get('port')); 
}); 

,這是我的藝術家模型

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

var artistSchema = new mongoose.Schema({ 
    name: String, 
    fpimage: String 

}); 

artistSchema.plugin(autoIncrement, 'Artist'); 
module.exports = mongoose.model('Artist', artistSchema); 

當我運行該應用程序,我得到以下錯誤消息

fn(this, opts); 
^

TypeError: fn is not a function 
    at Schema.plugin (C:\Users\tjesu\Desktop\pidal\auto-increment\node_modules\mongoose\lib\schema.js:1060:3) 
    at Object.<anonymous> (C:\Users\tjesu\Desktop\pidal\auto-increment\models\artist.js:10:14) 
    at Module._compile (module.js:541:32) 
    at Object.Module._extensions..js (module.js:550:10) 
    at Module.load (module.js:458:32) 
    at tryModuleLoad (module.js:417:12) 
    at Function.Module._load (module.js:409:3) 
    at Module.require (module.js:468:17) 
    at require (internal/module.js:20:19) 
    at Object.<anonymous> (C:\Users\tjesu\Desktop\pidal\auto-increment\app.js:4:14) 
    at Module._compile (module.js:541:32) 
    at Object.Module._extensions..js (module.js:550:10) 
    at Module.load (module.js:458:32) 
    at tryModuleLoad (module.js:417:12) 
    at Function.Module._load (module.js:409:3) 
    at Module.runMain (module.js:575:10) 

我該如何解決這個錯誤?我該怎麼辦?

回答

0

the docs,它看起來像你錯過了兩件事情:

需要初始化自動增量:

autoIncrement.initialize(mongoose.connection); 

您需要將您的電話更改爲:

artistSchema.plugin(autoIncrement.plugin, 'Artist'); 
0

使用autoIncrement.plugin而不是autoIncrement在您的模型中

,如:

artistSchema.plugin(autoIncrement.plugin, 'Artist'); 

,需要初始化自動增量一次

var connection = mongoose.createConnection("mongodb://localhost/auto-increment"); 

autoIncrement.initialize(connection); 

,並且可以使用得到像

app.get('/', function(req, res){ 
    var artist = new Artist({name: "Telmuun",fpimage: "Cover"}); 
    artist.save(function(err, saved) { 
    if(err) { 
     console.log(err); 
    } 
    else { 
     res.send('saved'); 
    } 
    }); 
});