我是MEANJS的新人:我正在用meanJS技术建立一个todolist。我从服务器端开始。当我运行我的server.js文件时,我收到以下错误:
node_modules\mongoose\lib\index.js:395
throw new mongoose.Error.MissingSchemaError(name);
^
MissingSchemaError: Schema hasn't been registered for model "Todo".
Use mongoose.model(name, schema)
at Mongoose.model (D:\meanjs\todolist\node_modules\mongoose\lib\index.js:395:13)
at Object.<anonymous> (D:\meanjs\todolist\server\api\todo.js:5:23)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (D:\meanjs\todolist\server\api\index.js:3:21)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
这是我的server.js文件:
//Import dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
//Connect to mongoDB server
mongoose.connect('mongodb://localhost/todoApp');
mongoose.set('debug', true);
//Get our API routes
const api = require('./server/api/');
//Require the models
require('./server/models/task.model'); //HERE
require('./server/models/todo.model'); //HERE
//Init express
const app = express();
//Set API routes
app.use('/api', api);
//Enable bodyParser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
//Enable CORS
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
next();
});
//Get environment port or use 3000
const port = process.env.PORT || '3000';
app.set('port', port);
//Create HTTP server.
const server = http.createServer(app);
//Listen on port
server.listen(port, () => console.log(`API running on localhost:${port}`));
我在server / api项目目录中有三个文件。 index.js
var router = require('express').Router();
router.use('/todo', require('./todo'));
router.use('/todo/task', require('./task'));
module.exports = router;
task.js
"use strict";
const router = require('express').Router();
const mongoose = require('mongoose');
const Todo = mongoose.model('Todo');
const Task = mongoose.model('Task');
router.param('task', function (req, res, next, id) {
if (!id.match(/^[0-9a-fA-F]{24}$/)) {
return res.sendStatus(422);
}
Task.findById(id).then((task) => {
if (!task) { return res.sendStatus(404); }
req.task = task;
return next();
})
});
router.post('/', (req, res) => {
if (!req.body.todoId || !req.body.content) {
res.sendStatus(422);
}
if (!req.body.todoId.match(/^[0-9a-fA-F]{24}$/)) {
res.sendStatus(422);
}
Todo.findById(req.body.todoId).then((todo) => {
if (!todo) { res.statusCode(404); }
let task = new Task();
task.content = req.body.content;
task.state = false;
task.todo = todo;
task.save().then(() => {
todo.tasks.push(task);
todo.save().then(() => {
res.json(task.toDto()).statusCode(201);
});
});
});
});
router.put('/', (req, res) => {
if (req.body.state == undefined || !req.body.id) {
res.sendStatus(422);
}
if (!req.body.id.match(/^[0-9a-fA-F]{24}$/)) {
res.sendStatus(422);
}
Task.findById(req.body.id).then((task) => {
task.state = req.body.state;
task.save().then(() => {
res.json(task.toDto()).statusCode(200);
})
})
});
router.delete('/:task', (req, res) => {
let task = req.task;
task.remove().then(() => {
res.sendStatus(200);
});
});
todo.js
"use strict";
const router = require('express').Router();
const mongoose = require('mongoose');
const Todo = mongoose.model('Todo');
const Task = mongoose.model('Task');
router.param('todo', function (req, res, next, id) {
if (!id.match(/^[0-9a-fA-F]{24}$/)) {
return res.sendStatus(422);
}
Todo.findById(id)
.populate('tasks')
.then(function (todo) {
if (!todo) { return res.sendStatus(404); }
req.todo = todo;
return next();
});
});
router.get('/', (req, res) => {
Todo.find()
.populate('tasks')
.then((todos) => {
if (!todos) { return res.sendStatus(404); }
return res.json({
todos: todos.map((todo) => {
return todo.toDto();
})
}).statusCode(200);
});
});
router.post('/', (req, res) => {
if (!req.body.title) {
res.sendStatus(422);
}
let todo = new Todo();
todo.title = req.body.title;
todo.save().then(() => {
res.json(todo.toDto()).statusCode(201);
})
});
router.delete('/:todo', (req, res) => {
req.todo.remove().then(function () {
return res.sendStatus(200);
});
});
我在服务器/模型中有两个定义每个模型的文件。 todo.model.js
const mongoose = require('mongoose');
const Task = mongoose.model('Task','TaskSchema');
let TodoSchema = new mongoose.Schema({
title: { type: String, required: [true, "can't be blank"], index: true },
tasks: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Task' }]
}, { timestamps: true });
TodoSchema.pre('remove', (next) => {
Task.remove({ todoId: this._id }).exec();
next();
})
TodoSchema.methods.toDto = function () {
return {
id: this._id,
title: this.title,
tasks: this.tasks.map((task) => {
return task.toDto();
})
}
}
mongoose.model('Todo', TodoSchema);
task.model.js
const mongoose = require('mongoose');
let TaskSchema = new mongoose.Schema({
content: { type: String, maxlength: 200 },
state: { type: Boolean, default: false },
todo: { type: mongoose.Schema.Types.ObjectId, ref: 'Todo' }
}, { timestamps: true });
TaskSchema.methods.toDto = function () {
return {
id: this._id,
content: this.content,
state: this.state
}
};
mongoose.model('Task', TaskSchema);
我错在哪里?
答案 0 :(得分:1)
//Get our API routes
const api = require('./server/api/');
//Require the models
require('./server/models/task.model'); //HERE
require('./server/models/todo.model'); //HERE
更改订单
//Require the models
require('./server/models/task.model'); //HERE
require('./server/models/todo.model'); //HERE
//Get our API routes
const api = require('./server/api/');
答案 1 :(得分:0)
在架构文件(task.model.js&amp;&amp; todo.model.js)中,您没有导出模型。在这两个文件中,您需要添加以下内容:
// models/todo.model.js
module.exports = mongoose.model('Todo', TodoSchema);
// models/task.model.js
module.exports = mongoose.model('Task', TaskSchema);
删除server.js中的无关要求:
require('./server/models/task.model'); // GET RID OF THIS
require('./server/models/todo.model'); // GET RID OF THIS
同样在todo.js和task.js中,既然你现在要导出模型,你必须像这样导入模型:
const Todo = require('../models/task.model')
const Task = require('../models/todo.model')
注意:这假设我的目录结构正确。
-server
-api
-models