gpt4 book ai didi

node.js - Nodejs 中 mongoose 出现 ".post is not a function"错误

转载 作者:太空宇宙 更新时间:2023-11-03 23:58:32 34 4
gpt4 key购买 nike

我用 Mongoose 在 Nodejs Express 上做了一个路由器。

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

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

TypeError: matching.post is not a functionat router.post (D:\Dev\matching\matching\routes\match ing.js:24:20)at 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);
}
});

我还添加了架构模型。
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);

最佳答案

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

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

此外,您不需要调用 wait (不确定为什么要这样做)。仅在执行 save 后调用。

来自docs :

post middleware are executed after the hooked method and all of its pre middleware have completed.

关于node.js - Nodejs 中 mongoose 出现 ".post is not a function"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55890809/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com