如果我们在Node.js中有多个模型文件,该如何获取数据

时间:2019-07-13 18:12:29

标签: node.js express

我有一个路由文件 user.js 和2个模型文件, hmscategory.js todo.js 。当我按下http://localhost:5000/user/todo时,我正在从db中获取数据,但是当我按下http://localhost:5000/user/hmscategory时,则未获得任何数据。


user.js

const Category = require('../models/hmscategory');
const Todo = require('../models/todo');

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

router.get('/hmscategory', (req, res, next) => {
    Category.find({})
        .then(data => res.json(data))
        .catch(next)
});

router.get('/todo', (req, res, next) => {
    // this will return all the data, 
    // exposing only the id and action field to the client
    Todo.find({})
        .then(data => res.json(data))
        .catch(next)
});

module.exports = router;

todo.js

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

//create schema for todo
const TodoSchema = new Schema({
    action: {
        type: String,
        required: [true, 'The todo text field is required']
    }
})

//create model for todo
const Todo = mongoose.model('todos', TodoSchema);

module.exports = Todo;

hmscategory.js

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

//create schema for todo
const CategorySchema = new Schema({
    category_name: {
        type: String,
        required: [true, 'The todo text field is required']
    }
})

//create model for todo
const Category = mongoose.model('category', CategorySchema);

module.exports = Category;

0 个答案:

没有答案