node.js - 在 post web service bill 中查找现有的 id 对象
问题描述
我想在发布账单时找到一个现有的 id 对象,但我不知道如何找到它来保存账单。我希望它从后端和前端工作。
这是我的账单模型:
const mongoose = require("mongoose");
const { Schema } = mongoose;
const billSchema = new Schema({
number: Number,
date: { type: Date, default: Date.now() },
type: String,
local: String,
client: {
type: mongoose.Schema.Types.ObjectId,
ref: "clients"
},
provider: {
type: mongoose.Schema.Types.ObjectId,
ref: "providers"
},
detail: [
{
quantity: Number,
product: {
code: Number,
name: String,
price: Number
},
undertotal: Number
}
],
total: Number
});
module.exports = mongoose.model("bills", billSchema);
这是我的邮政服务:
app.post("/api/bills", async (req, res) => {
const { number, type, local, detail, total } = req.body;
let existingClient = await Client.findById(Client._id);
if (!existingClient) {
return res.status(404).json({
message: "not found client"
});
}
let existingProvider = await Provider.findById(Provider._id);
if (!existingProvider) {
return res.status(404).json({
message: "not found provider"
});
}
if (
!existingClient._id ||
(existingClient._id &&
mongoose.Types.ObjectId() ===
(await Client.findById(existingClient._id).select("_id")))
) {
const clientId = mongoose.Types.ObjectId();
this.existingClient._id = clientId;
}
if (
!existingProvider._id ||
(existingProvider._id &&
mongoose.Types.ObjectId() ===
(await Provider.findById(existingProvider._id).select("_id")))
) {
const providerId = mongoose.Types.ObjectId();
this.existingProvider._id = providerId;
}
const bill = new Bill({
number,
date: new Date(),
type,
local,
client: clientId,
provider: providerId,
detail,
total
});
try {
let newBill = await bill.save();
res.status(201).send(newBill);
} catch (err) {
if (err.name === "MongoError") {
res.status(409).send(err.message);
}
console.log(err);
res.status(500).send(err);
}
});
预期输出是使用客户端和提供者 ID 保存的账单,但实际输出是一条错误消息,指出“无法读取未定义的属性 _id”
怎么了?
解决方案
推荐阅读
- android - 使函数等待/阻塞然后发出信号以从另一个函数继续的最佳方法
- django - Django通过循环遍历日期范围的每一天进行过滤
- javascript - 构造函数是类的静态方法吗?
- python - 字典列表上的返回值
- templates - 无法使用“添加到愿望清单”和“添加到比较”按钮获取相关产品
- javascript - React - 在减速器中缓存数据?
- kotlin - 未找到 bdd 功能外键
- javascript - 如何让函数从 mousedown 执行到 mouseup 或 mouseleave
- wolfram-mathematica - 在特定情况下测试真相。使用文档编写正确的输入并解释输出
- css - CSS:导航栏下拉菜单固定与粘性意外行为