【问题标题】:The error of ".post is not a function" with mongoose at NodejsNodejs 的 mongoose 出现“.post 不是函数”的错误
【发布时间】:2019-09-17 08:05:34
【问题描述】:

我用 Mongoose 在 nodejs express 上做了一个路由器。

当我通过邮递员发送const { clientID, orderID } = req.body; 时,

await matching.save(); 运行良好。 但之后它会出现如下错误。
我该如何解决这个问题?

TypeError:matching.post 不是函数 在 router.post (D:\Dev\matching\matching\routes\match ing.js:24:20) 在 process._tickCallback (internal/process/next_tick.js:68:7)

var express = require("express");
var router = express.Router();
const Matching = require("./../models/matching");

function wait(time) {
  return new Promise(resolve => {
    setTimeout(resolve, time);
  });
}

router.post("/orderpost", async (req, res, next) => {
  try {
    const { clientID, orderID } = req.body;
    const listOn = true;

    const matching = new Matching({
      clientID,
      orderID,
      listOn
    });

    await matching.save();

    await matching.post("save", (doc, next) => {
      wait(3000).then(() => {
        console.log("good");
        next();
      });
    });

    res.send("good");
  } catch (err) {
    console.error(err);
  }
});

我还添加了 Schema 模型。
const mongoose = require("mongoose");

const { Schema } = mongoose;
const MatchingSchema = new Schema({
  clientID: String,
  riderID: [String],
  orderID: String,
  listOn: Boolean
});

module.exports = mongoose.model("Matching", MatchingSchema);

【问题讨论】:

  • 你的Matching是什么,是Schema还是Model,貌似是后者,能不能也把代码贴在models/matching@
  • 我附上了,非常感谢您的关注!

标签: node.js mongoose


【解决方案1】:

post 方法适用于 Schema 而不是 Model。应该在您的架构上调用它。

MatchingSchema.post("save", (doc) => {
  console.log("good");
});

你也不需要打电话给wait(不知道你为什么这样做)。只有在save 执行后才会调用它。

来自docs

post 中间件在钩子方法及其所有前置中间件完成后执行。

【讨论】:

  • 感谢您的回答。我还有一个问题。如何从其他 .js 文件中读取 Schema? Bcz 我从另一条路径导入了模式模型。我必须将架构放在 router.js 中吗?
  • 您可以将 post 挂钩放在您定义架构的 matching 文件中。
猜你喜欢
  • 2021-08-28
  • 2011-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-27
  • 2021-01-25
  • 1970-01-01
  • 2021-04-22
相关资源
最近更新 更多