提问人:Ziv 提问时间:11/17/2023 最后编辑:Ziv 更新时间:11/18/2023 访问量:68
如何修复猫鼬Model.create永远卡住
How to fix mongoose Model.create being stuck forever
问:
我不明白为什么猫鼬不能完成这个Model.create。
相同的连接适用于其他控制器功能
我正在尝试创建一个新文档,但我的代码卡住了 而且我无法得到任何错误来找出问题所在
const createNote = async (req, res) => {
try {
const { user, title, text } = req.body
if (!user || !title || !text) {
return res.status(400).json({ text: 'all fileds are required' })
}
console.log('got here')
const userId = new mongoose.Types.ObjectId(user)
const newNote = await Note.create({ user: userId, title, text })
console.log("got here 1")
if (!newNote) {
return res.status(400).json({ message: 'note not created' })
}
res.status(200).json({ message: `new note created for ${user} ` })
}
catch (e) {
console.error("error handling note creation: ", e);
res.status(500).send()
}
}
const noteSchema = new mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User',
},
title: {
type: String,
required: true,
},
text: {
type: String,
default: true,
},
completed: { type: Boolean, default: false },
},
{
timestamps: true,
}
);
noteSchema.plugin(autoIncrement, {
inc_field: 'ticket',
id: 'ticketNums',
start_seq: 500,
});
module.exports = mongoose.model('Note', noteSchema);
答:
0赞
jlacab
11/17/2023
#1
我建议处理承诺,这样你就可以尝试弄清楚发生了什么。
评论
0赞
Sam Spade
11/17/2023
实际上,我确实认为他正确地使用了这些承诺。 正是文档中调用函数的方式: mongoosejs.com/docs/api/model.html#Model.create() 此外,该函数本身返回一个 promise,所以他肯定不是“让它成为 promise”await model.create()
model.create()
await
0赞
Tyler2P
11/17/2023
通过提供解决方案的示例以及它如何帮助 OP,可以改进您的答案。
0赞
Sam Spade
11/17/2023
#2
所以我看不到你的Note模式,但我假设该字段应该具有类型,也就是说,对你在其他地方定义的模型的引用。但在您提供的代码示例中,您似乎给了它一个 mongoID 字符串。user
Ref<User>
User
如果添加以下行,脚本应开始工作。这会将您的用户变量从 mongo ObjectID 的字符串表示形式转换为真正的 mongo ObjectID。:
user = new mongoose.Types.ObjectId(user);
但是,我认为您的主要问题实际上只是您没有收到错误打印输出。我的猜测是使错误消失了。如果将函数的主体放在 try catch 块中,并在 catch 中带有 console.error,则将来应该能够看到该错误asyncHandler
const createNote = asyncHandler(async (req, res)=>{
try{
// your code here
} catch(e){
console.error("error handling note creation: ", e);
res.status(500).send()
}
})
这主要是猜测,因为我没有太多的背景。如果这不能解决问题,请发布您的模型的架构以及您获得的任何错误打印输出。Note
评论
0赞
Ziv
11/18/2023
感谢您的回复,您的假设是正确的,如果我用新的猫鼬包裹用户,我仍然会得到同样的反应。Types.Objectid。 即使在获取 catchasync 的 idingr id 之后,我仍然停留在发送请求上
0赞
Sam Spade
11/21/2023
@Ziv尝试删除自动递增插件
评论