我正在创建一个后钩创建一个鼻涕虫后,一个后已保存.当我try 使用Postman判断我的结果时,过程进入不确定状态(没有返回数据).

POST挂钩的代码:

PostsSchema.post("save", async function (doc, next) {
  try {
    doc.postSlug = slugify(doc.postTitle, { lower: true });
    await doc.save();
    return next();
  } catch (err) {
    console.log("inside catch method");
    return next(createError(500, err.message));
  }
});

我使用的路由代码:

module.exports.createPost = async (req, res, next) => {
  const { postTitle, postContent, postAuthor } = req.body;
  try {
    // check if author exist
    const authorExist = await AccountsModel.findById(postAuthor);
    if (!authorExist) {
      return next(createError(404, `Author ID: ${postAuthor} Not Found`));
    }
    // create post
    console.log("route 1")
    const postNew = new PostsModel({
      postTitle: postTitle,
      postContent: postContent,
      postAuthor: postAuthor,
    });
    await postNew.save();
    // populate data for return
    let postCreated = await postNew.populate("postAuthor");
    return res.status(200).json({
      code: 1,
      success: true,
      message: "New Post Created",
      data: postCreated,
    });
  } catch (error) {
    return next(createError(500, error.message));
  }
};

我确实通过删除doc.save()前面的await来解决这个问题:

PostsSchema.post("save", async function (doc, next) {
  try {
    doc.postSlug = slugify(doc.postTitle, { lower: true });
    doc.save();
    return next();
  } catch (err) {
    console.log("inside catch method");
    return next(createError(500, err.message));
  }
});

另外,使用.then()也返回结果:

PostsSchema.post("save", async function (doc, next) {
  doc.postSlug = slugify(doc.postTitle, { lower: true });
  console.log(1);
  doc
    .save()
    .then(() => {
      console.log(2);
      return next();
    })
    .catch((error) => {
      return next(createError(500, err.message));
    });
});

但发现了一些其他的帖子,什么已经等待和答案表明,这不是问题:

所以,我想知道是等待打破了这个过程还是别的什么?

推荐答案

我发现了问题,当我console.log(1)在你的POST钩子,它创建了一个无限循环.根据POST Mongoose post save hook , update the document的1下的注释,POST钩子在执行.save()之后执行;在您的POST钩子内,您执行另一个.save(),它再次调用您的POST钩子,从而创建无限循环.

你的await doc.save()不工作,因为它在等待无限循环完成.这就是为什么postman 没有回应,它从来没有到达return next()部分.

你的doc.save()"工作"是因为.save()是异步的;在它完成它的过程之前,它已经到达了return next()部分,这就是为什么在代码停留在无限循环中时,会有一个值返回给postman.

你的doc.save().then()"工作",因为.then()解析了你的.save()并到达return next(),但它再次调用了post钩子,创建了一个无限循环.

我建议更改挂接中的关键字PASS或更改为前挂接:

PostsSchema.pre('save', function(next) {
    if (this.isNew || this.isModified('PostTitle')) {
        this.slug = slugify(this.PostTitle, { lower: true });
    }
    return next();
});

这个预挂接在实际的save()操作之前运行,所以在保存它之后不会再次调用该挂接.

Javascript相关问答推荐

可以的.是否可以在不预编译的情况下使用嵌套 Select 器?

node TS:JWT令牌签名以验证客户端和后台问题之间的身份验证

Redux查询多个数据库Api reducerPath&

使用useEffect,axios和useParams进行react测试

自定义高图中的x轴标签序列

屏幕右侧屏障上的产卵点""

如何将react—flanet map添加到remixjs应用程序

您能在卸载程序(QtInsteller框架)上添加WizardPage吗?

如何将多维数组插入到另一个多维数组中?

如何将innerHTML字符串修剪为其中的特定元素?

以Angular 实现ng-Circle-Progress时出错:模块没有导出的成员

映射类型定义,其中值对应于键

打字脚本中方括号符号属性访问和拾取实用程序的区别

TabNavigator和StackNavigator之间的Reaction Native中的导航问题

如何在Highlihte.js代码区旁边添加行号?

在使用JavaScript以HTML格式显示Google Drive中的图像时遇到问题

REACT-本机错误:错误类型错误:无法读取未定义的容器的属性

如何将值从后端传递到前端

react :图表负片区域不同 colored颜色

正在发出错误的URL请求