英文:
I am trying to create a doc to model with mongoose but model.create() does not return any promise
问题
代码中的问题似乎在于model.create()
方法未返回任何Promise,导致无法处理。这可能导致了始终返回500错误,而不提供具体的错误信息。要解决此问题,您可以尝试将model.create()
包装在一个Promise中,如下所示:
exports.create = async (req, res) => {
const password = await hash(req.body.password);
const rawUser = {
...req.body,
password,
};
try {
const user = await User.create(rawUser);
const newUser = user.toObject();
res.send(newUser);
} catch (err) {
if (err.code === 11000) {
res.status(400).send({ message: 'A user with this email address has already registered.' });
} else {
res.status(500).send({ message: 'An unexpected error occurred' });
}
}
};
通过这种方式,您可以更好地处理错误并获得更具体的错误信息。
英文:
it seems that the create method does not return any promise that then can handle
I tried different things but nothing worked
this is my routes file
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const express = require("express")
const router = express.Router();
const controller = require("./controller")
router.post("/signup", controller.create);
module.exports = router;
<!-- end snippet -->
and this is my model file
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const mongoose = require('mongoose');
const User = new mongoose.Schema(
{
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
picture: {
type: String
},
password: {
type: String,
select: false
},
email: {
required: true,
type: String,
unique: true
}
},
{
timestamps: true
}
);
User.index({
firstName: 'text',
lastName: 'text',
});
module.exports = mongoose.model('User', User);
<!-- end snippet -->
and this is the controller file
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const User = require('./model');
const { hash, compareHash } = require('../lib/util');
const { createToken, findUserByToken } = require('../lib/auth');
const cookieIsSecure = process.env.ENVIRONMENT === 'production';
exports.create = async (req, res) => {
const password = await hash(req.body.password);
const rawUser = {
...req.body,
password,
};
User.create(rawUser)
.then(async user => {
return user.save();
})
.then(async user => {
const newUser = user.toObject();
res.send(newUser);
})
.catch(err => {
if (err.code === 11000) {
res.status(400).send({ message: 'A user with this email address has already registered.' });
return;
}
res.status(500).send({ message: 'An unexpected error occurred' });
});
};
<!-- end snippet -->
it always return the 500 error "an unexpected error occurred"
which is not really specific. and i do not know what is the problem exactly. but I am sure it has something to do with the model.create() it does not return any promise.
答案1
得分: 2
这里你混合了方法。 create
方法不需要 save
,因为它是隐式的:
https://mongoosejs.com/docs/api.html#model_Model.create
请尝试这样做,我已经对你的代码进行了一些重构,并添加了更容易阅读和使用的 try/catch:
const rawUser = new User({ ...req.body, password});
try {
await rawUser.save();
res.status(201).send(newUser);
} catch(err) {
if (err.code === 11000) return res.status(400).send({ message: '此电子邮件地址的用户已经注册过了。' });
res.status(500).send({ message: '发生了意外错误' });
}
英文:
Here you are mixing methods. create
doesn't want save
in it as it's implicit:
https://mongoosejs.com/docs/api.html#model_Model.create
Please try this, I've refactored your code a bit and added much easier to read and use try/catch:
const rawUser = new User({ ...req.body, password});
try {
await rawUser.save();
res.status(201).send(newUser);
} catch(err) {
if (err.code === 11000) return res.status(400).send({ message: 'A user with this email address has already registered.' });
res.status(500).send({ message: 'An unexpected error occurred' });
}
答案2
得分: 1
你需要像这样使用 async/await:
exports.create = async (req, res) => {
try {
const password = await hash(req.body.password);
const rawUser = {
...req.body,
password
};
const user = await User.create(rawUser);
const newUser = user.toObject();
res.send(newUser);
} catch (err) {
console.log("ERROR: ", err);
if (err.code === 11000) {
return res.status(400).send({
message: "A user with this email address has already registered."
});
}
res.status(500).send({ message: "An unexpected error occurred" });
}
};
英文:
You need to use async/await like this:
exports.create = async (req, res) => {
try {
const password = await hash(req.body.password);
const rawUser = {
...req.body,
password
};
const user = await User.create(rawUser);
const newUser = user.toObject();
res.send(newUser);
} catch (err) {
console.log("ERROR: ", err);
if (err.code === 11000) {
return res.status(400).send({
message: "A user with this email address has already registered."
});
}
res.status(500).send({ message: "An unexpected error occurred" });
}
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论