我尝试在 Node 中使用带有 Mongoose 的外部架构,但不断收到此错误:
ReferenceError: ContactSchema is not defined
我的 ContactSchema.js 看起来像这样:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ContactSchema = new Schema({
name: String,
address: String
});
module.exports = mongoose.model('ContactSchema', ContactSchema);
我的routes.js 文件如下所示:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/choredb');
require('../models/ContactSchema.js');
var routes = function(app) {
app.post('/createnew', function(req, res) {
console.log(req.body);
var contact = new ContactSchema();
contact.name = req.body.name;
contact.note = req.body.note;
contact.save(function(err){
if (err) {throw err;}
console.log('saved');
mongoose.disconnect();
});
});
}
module.exports = routes;
我很确定它并不遥远,但无法弄清楚为什么它找不到架构。
最佳答案
如果您在“example_module”中导出某些内容,则 require(“example_module”) 将返回某些内容。您编写的代码返回内容模型,尽管您没有声明为变量。
我的代码方式是
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ContactSchema = new Schema({
name: String,
address: String
});
var Content = mongoose.model('Content', ContentScehma);
module.exports = Content;
在路由器或其他地方
app.post("/content", function(req, res, next){
var Content = require("../models/ContactSchema.js");
var ContentSchema = ContentModel.schema;
var aContent = new Content({name: "MyName", address: "MyAddress"});
aContent.save(function(err, savedContent){
if(err) return next(err);
return res.send(savedContent);
});
});
关于javascript - 引用错误: Schema is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31022156/