mongodb mongoose返回了一个错误:保存()不再接受回调

wwwo4jvm  于 2023-08-04  发布在  Go
关注(0)|答案(1)|浏览(133)
  1. const humanSchema = new mongoose.Schema({
  2. name:String,
  3. })
  4. const Human = mongoose.model('human',humanSchema)
  5. humanSchema.post('save',function(docs,next){
  6. console.log("A save function occured")
  7. next()
  8. })
  9. const h = new Human({name:"john"})
  10. h.save(function(err){
  11. console.log("logged")
  12. });

字符串
首先,有一个保存()不接受回调的错误,我正在学习如何使用post(),但它从不记录事件。
我希望post()函数记录“发生了一个保存函数”

qvtsj1bj

qvtsj1bj1#

首先,试着在编译模型之前定义你的中间件:
https://mongoosejs.com/docs/middleware.html#defining

  1. const humanSchema = new mongoose.Schema({
  2. name:String,
  3. })
  4. humanSchema.post('save',function(docs,next){
  5. console.log("A save function occured")
  6. next()
  7. })
  8. const Human = mongoose.model('human',humanSchema)

字符串
其次,如果你想在保存()之后运行一些东西,你需要用.then链接函数

  1. doc.save().then(savedDoc => {
  2. console.log('Doc saved');
  3. });


或者使用async/await(可能在try... catch块中)

  1. await doc.save();
  2. console.log('Doc saved');

展开查看全部

相关问题