未解决的函数或方法save()

时间:2019-09-30 03:56:55

标签: javascript node.js express mongoose

猫鼬model.save()方法未定义。

models / genre.js

'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const GenreSchema = new Schema({
    name: {type: String, required: true}
});

GenreSchema
    .virtual('url')
    .get(function () {
        return '/catalog/genre/' + this._id;
    });

module.exports = mongoose.model('Genre', GenreSchema);

controllers / genreController.js

'use strict';
var Genre = require('../models/genre');

module.exports = {

    genre_get: function (req, res) {
        res.render('catalog/createGenre');
    },
    genre_post: function (req, res) {
        var genre = new Genre(
            { name: req.body.name }
        );
        genre.save(function (err) {
            if (err) { return err; }
            res.redirect('catalog/genre/list');
        });
    }
};

错误

image of error

我尝试在喷气机上进行以下工作:

跟随他们,他们在控制器中说:

var Genre = require('../models/genre.js').Genre;

这解决了问题并解决了功能,但后来在以下位置发出发布请求时出现错误,提示Genre is not a constructor

`var genre = new Genre(
        { name: req.body.name }
    );`

已解决:只需这样做即可解决问题

var genre = mongoose.model('Genre', GenreSchema); module.exports = genre;

2 个答案:

答案 0 :(得分:0)

您应该使用这种方式

var Genre = require('../models/genre');

module.exports = {

    genre_get: function (req, res) {
        res.render('catalog/createGenre');
    },
    genre_post: function (req, res) {
        var genre = new Genre(
            { name: req.body.name }
        );
        genre.save((err , saved)=>{ \\updated
            if (err) { return err; }
            else{
               res.redirect('catalog/genre/list');
            } 
        });
    }
};

答案 1 :(得分:0)

{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsicGF5bWVudCIsImludmVudG9yeSJdLCJ1c2VyX25hbWUiOiJrcmlzaCIsInNjb3BlIjpbIlJFQUQiLCJXUklURSJdLCJuYW1lIjoibGFrc2hpdGhhIiwiZXhwIjoxNTY5OTI5MjI2LCJqdGkiOiJjNDlmMGZiZi1mY2ViLTQ3ZWEtYTYxMy04NTUwYjJlZmU1NzUiLCJjbGllbnRfaWQiOiJtb2JpbGUifQ.siryNGlQrDguWTxzs9Y3NsNPxl8a4hXd3hqZySQ0okk",
  "token_type": "bearer",
  "refresh_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsicGF5bWVudCIsImludmVudG9yeSJdLCJ1c2VyX25hbWUiOiJrcmlzaCIsInNjb3BlIjpbIlJFQUQiLCJXUklURSJdLCJhdGkiOiJjNDlmMGZiZi1mY2ViLTQ3ZWEtYTYxMy04NTUwYjJlZmU1NzUiLCJuYW1lIjoibGFrc2hpdGhhIiwiZXhwIjoxNTY5OTM1NjI2LCJqdGkiOiI4ODE2NDc3Yi02ZTk4LTRiZmEtYWEzYi0xYTYxNTZmYTlhYzIiLCJjbGllbnRfaWQiOiJtb2JpbGUifQ.2XEWC60M3GwSKyQFiF68EZlOANFwphcYWEi1hPAWPoA",
  "expires_in": 3599,
  "scope": "READ WRITE",
  "name": "test",
  "jti": "c49f0fbf-fceb-47ea-a613-8550b2efe575"
}