我是计算机语言的新手。我尝试从 Youtube 了解后端 Web 项目,但该视频是 2 年前发布的。现在 Mongoose 放弃了对 Model.prototype.save 的回调支持。
我尝试将新数据添加到数据库,它显示 Model.prototype.save() 不再接受回调。
如何重构代码以正确运行。
连接到 MongoDB
const dbUrl = 'mongodb://127.0.0.1:27017/productDB'
mongoose.connect(dbUrl,{
useNewUrlParser:true,
useUnifiedTopology:true
}).catch(err=>console.log(err))
添加新的数据模块
module.exports.saveProduct = function(model,data){
model.save(data)
}
router.post('/insert',(req,res)=>{
let data = new Product({
name:req.body.name,
price:req.body.price,
image:req.body.image,
description:req.body.description
})
Product.saveProduct(data,(err)=>{
if(err) console.log(err)
res.redirect('/')
})
})
错误显示:
throw new MongooseError('Model.prototype.save() 不再接受回调'); ^
许多 MongoDB 函数不再接受回调,因为 MongoDB 使用 Promise。它们或多或少被 .then() 和 .catch() 方法取代。
https://www.mongodb.com/docs/drivers/node/current/fundamentals/promises/
这段代码应该可以工作
Product.saveProduct().then(() => console.log("成功保存产品)).catch((err) => {res.send(err);});