【问题标题】:Node express API using class not inserting data使用不插入数据的类的节点快速 API
【发布时间】:2022-01-25 20:39:06
【问题描述】:

Node js 的新手,我正在使用 Node JS 构建 API 并使用 class。目前有2 routes,一个是fetch all users,它工作正常,另一个是insert new user,它不工作。是returning {} with status 500

这是文件。

index.js

import server from "./config/server.js";
import './config/database.js';

const PORT = process.env.PORT || 5000;
server.listen(PORT, () => {
  console.log(`app running on port ${PORT}`);
});

config/database.js

import mongoose from "mongoose";

class Connection {
  constructor() {
    const url =
      process.env.MONGODB_URI || `mongodb://localhost:27017/dev-muscles`;
    console.log("Establish new connection with url", url);
    mongoose.Promise = global.Promise;
    // mongoose.set("useNewUrlParser", true);
    // mongoose.set("useFindAndModify", false);
    // mongoose.set("useCreateIndex", true);
    // mongoose.set("useUnifiedTopology", true);
    mongoose.connect(url);
  }
}

export default new Connection();

config/server.js

    import express from "express";
    import UserController from "../src/models/controllers/UserController.js";

    const server = express();
    server.use(express.json());

    server.get(`/users`, UserController.getAll);
    server.post(`/users/create`, UserController.create);


    export default server;

src/models/User.js

import mongoose from "mongoose";
const { Schema } = mongoose;
import validator from "validator";

class User {
    initSchema() {
        const schema = new Schema({
            first_name: {
                type: String,
                required: true,
                trim: true
            },
            last_name: {
                type: String,
                required: true,
                trim: true
            },
            email: {
                type: String,
                required: true,
                trim: true,
                lowercase: true,
                // validate(value) {
                //     if( !validator.isEmail(value) ) {
                //         throw new Error('Email is invalid')
                //     }
                // }
            },
            phone: {
                type: Number,
                required: true,
                trim: true
            },
            password: {
                type: String,
                required: true
            }
        });
        
        // schema.plugin(validator);
        mongoose.model("users", schema);
    }

    getInstance() {
        this.initSchema();
        return mongoose.model("users");
    }
}

export default User;

src/controllers/UserController.js

import Controller from "./Controller.js";
import User from ".././models/User.js";
const userModelInstance = new User().getInstance();

class UserController extends Controller {

    constructor(model) {
        super(model);
    }
}

export default new UserController(userModelInstance);

src/controllers/Controller.js

class Controller {

    constructor(model) {
        this.model = model;
        this.getAll = this.getAll.bind(this);
        this.create = this.create.bind(this);
    }

    async getAll(req, res) {    // works fine
        return res.status(200).send(await this.model.find({}));
    }

    async create(req, res) {    // this is returning {} with status code 500
        try {
            // return res.send(req.body);
            return res.status(201).send(await new this.model.save(req.body));
        } catch (error) {
            res.status(500).send(error);
        }
        
    }

}

export default Controller;

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    像这样重构create 方法。

    const ItemToSave = new this.model(req.body); 
    
    const savedItem = await ItemToSave.save();
    
    return res.status(201).send(savedItem);
    

    【讨论】:

    • 得到相同的结果。 {} with status code 500
    • 改为这样做。 const ItemToSave = new this.model(req.body); ItemToSave.save((err) => { if(err) return res.status(400).send(err); }); return res.status(201).send(ItemToSave);
    • 嘿,这行得通....但是之前的代码有什么问题?
    • 明白。我重构了create 方法并将try 块下的行更改为return res.status(201).send(await new this.model(req.body).save());,并且它起作用了。谢谢
    • 我认为最好使用打字稿来避免像这样的实现方法
    猜你喜欢
    • 2018-04-17
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多