猫鼬:.save不是函数

时间:2016-07-01 17:12:22

标签: javascript node.js mongodb express mongoose

我很新,我查看了档案,但是这段代码中发生的事情让我望而却步。我使用快速生成器来创建日历应用程序,现在我想将它连接到MongoDB。与Mongo的实际连接正在运行,但我无法保存文档。

global.js 的相关部分(我运行我的前端Javascript)看起来像这样:

$(document).ready(function() {

var ev = new Event({ date: "a6_13_2016", time: 900, description:"Fencing"});
    ev.save(function(err) {
        if (err) console.log(err);
        else console.log("Success!")
    })

这是我得到" TypeError:ev.save不是函数"信息。我的 models / Events.js 如下所示:

var mongoose = require('mongoose');

var eventSchema = new mongoose.Schema({
    date: String,
    time: Number,
    description: String
});

 module.exports = mongoose.model('Event', eventSchema);

我的 routes / events.js 如下所示:

var express = require('express');
var router = express.Router();

var mongoose = require('mongoose');
var Event = require('../models/Events.js');

/* GET /event listing. */
router.get('/', function(req, res, next) {
  Event.find(function (err, dates) {
    if (err) return next(err);
    res.json(dates);
  });
});

/*POST event*/
router.post('/', function(req, res, next) {
  Event.create(req.body, function (err, post) {
    if (err) return next(err);
    res.json(post);
  });
});

/* GET /event/id */
router.get('/:id', function(req, res, next) {
  Event.findById(req.params.id, function (err, post) {
    if (err) return next(err);
    res.json(post);
  });
});

module.exports = router;

我想保存一些东西来测试它,但是它给了我" .save不是一个功能。

以外
var events = require('./routes/events');
app.use('/events', events); 

和建立Mongoose连接的代码我的 app.js 文件是样板文件。您认为这是什么问题?

2 个答案:

答案 0 :(得分:3)

I see

$(document).ready(function() {

Are you trying to use Mongoose in browser?

It's supposed to be used on the server-side.

In browser you need to send AJAX request to the server:

$('#save').click(function() {
    $.post('/event', function(response) { console.log(reposne) })
});

On the server you should add a route that will handle your AJAX request, and inside this route you can save your model:

router.post('/event', function(req, res) {
  var ev = new Event({ date: "a6_13_2016", time: 900, description:"Fencing"});
    ev.save(function(err) {
        if (err) console.log(err);
        else console.log("Success!")
    })
});

Please note that you don't need the 3rd param next in your rotues. It is used only in middlewares

答案 1 :(得分:0)

你确定该行

var Event = require('../models/Events.js');

有正确的路径吗?

您正在使用Event函数创建一个ev对象,从错误描述来看,似乎未定义ev。

如果您的事件文件未正确加载,您将无法访问.save函数。