Mongoose .save() 返回空的错误对象,不保存在数据库中 [英] Mongoose .save() returns empty error object, does not save in DB

查看:28
本文介绍了Mongoose .save() 返回空的错误对象,不保存在数据库中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习 MongoDB 和 typescript,但目前在尝试创建我的第一个文档时遇到了一些问题.

I am trying to learn MongoDB and typescript but currently running into some issues when trying to create my first document.

当我从邮递员处发出邮寄请求时,我收到发送请求";5 秒,然后超时并返回一个空的错误对象:

When I make a post request from postman, I get "Sending request" for 5 seconds, then it times out and returns an empty error object:

{
    "message": {}
}

并且发布的数据没有保存在我的 mongoDB 中.

and the posted data is not saved in my mongoDB.

我首先在我的服务器中建立这样的连接:

I first set up connection like this in my server:

mongoose.connect(<string> process.env.DB_CONNECTION, { useNewUrlParser: true}, () =>
    console.log("connected to DB!")
);

并取回记录的正确语句,因此我已连接.

and get back the correct statement logged, so I am connected.

我有一个看起来像这样的模型:

I have a model that looks like this:

import { model, Schema, Model, Document } from "mongoose";

export interface IUser extends Document {
    name: string,
}

const UserSchema: Schema = new Schema(
    {
        name: {
            type: Schema.Types.String,
            required: true,
        },
    },
    <any> {timeStamps: true}
);

const User: Model<IUser> = model<IUser>('User', UserSchema);
export default User;

问题可能出在那里,但我认为不是.

The problem could be in there, but I don’t think it is.

然后,这是我调用的端点的发布请求:

Then, here is my post request for the endpoint I call:

router.post('/add', async (req: Request, res: Response): Promise<any> => {
    try {
        const user: IUser = new User({
            name: req.body.name
        });

        const savedUser: IUser = await user.save();

        res.status(200).json(savedUser);
    } catch (err: any) {
        res.status(500).json({message: err});
        console.log("There was an error");
    }
})

这是我认为错误的地方,因为每次请求卡在等待 .save() 时

Here is where I believe the error is becuase every time the request gets stuck on awaiting the .save()

任何帮助都会很棒!谢谢!

Any help would be great! Thanks!

推荐答案

问题在于初始数据库连接,密码包含未编码的字符.编码特殊字符的一种解决方案是使用内置的 encodeURIComponent() 函数.

The issue was with the initial database connection, the password contained characters that that weren't being encoded. One solution to encode special characters is to make use of the built-in encodeURIComponent() function.

这篇关于Mongoose .save() 返回空的错误对象,不保存在数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆