猫鼬中的自动增量字段

时间:2016-08-23 12:27:50

标签: node.js mongodb mongoose

我试图在猫鼬中创建自动增量字段,但由于某种原因我无法创建

这是我的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)

我该如何解决此错误?我该怎么办?

2 个答案:

答案 0 :(得分:0)

the docs开始,您似乎错过了两件事:

您需要初始化autoIncrement:

autoIncrement.initialize(mongoose.connection);

您需要将通话更改为:

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

答案 1 :(得分:0)

在模型中使用autoIncrement.plugin代替autoIncrement

像:

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

并且需要初始化autoIncrement一次

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

autoIncrement.initialize(connection);

可以使用get like

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');
    }
  });
});