Reputation: 135
I am trying to learn MongoDB and typescript but currently running into some issues when trying to create my first document.
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": {}
}
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");
}
})
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!
Upvotes: 0
Views: 1469
Reputation: 4034
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.
Upvotes: 1