我正在用MEAN堆栈编写Web应用程序,而猫鼬实例使我头疼。
这是我的代码(部分):
我的路线
var express = require('express');
var router = express.Router();
var accDocService = require('../services/accdoc-services');
router.post('/dailybook', function(req, res) {
accDocService.addAccDoc(req.body, function(error) {
if (error) throw error;
});
});
accdoc-service.js
var accDoc = require('../models/accdoc').accDoc;
console.log(typeof accDoc);
exports.addAccDoc = function(accDoc, next) {
var newAccDoc = new accDoc({
number: '45645'
});
newAccDoc.save(function(error) {
if (error) throw error;
console.log("doc created");
});
};
accdoc.js(模型文件)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var accDocSchema = new Schema({
number: String
});
var accDoc = mongoose.model('accDoc', accDocSchema);
module.exports = {
accDoc: accDoc
};
发送发帖请求后,我得到
TypeError: accDoc is not a function
另外,第二个文件中的
console.log(typeof accDoc);
返回函数。编辑1
在accdoc-services中,如果将
var AccDoc = require('../models/accdoc');
移至addAccDoc
函数,则一切正常。我在这里缺少一些node.js的东西吗?我正在观看Lynda的教程视频,那里没有像这样的示波器问题。
here is an image from Lynda tutorial
最佳答案
您缺少用于创建accDoc模型实例的new关键字
var accDoc = require('../models/accdoc').accDoc;
console.log(typeof accDoc);
exports.addAccDoc = function(accDoc, next) {
var newAccDoc = new accDoc({ // HERE new was missing!
number: '45645'
});
newAccDoc.save(function(error) {
if (error) throw error;
console.log("doc created");
});
};