Node.js 在post web service bill中查找现有id对象
我想在发布账单时找到一个现有的id对象,但我不知道如何找到它来保存账单。我希望它从后端和前端工作 这是我的账单模型:Node.js 在post web service bill中查找现有id对象,node.js,mongoose,Node.js,Mongoose,我想在发布账单时找到一个现有的id对象,但我不知道如何找到它来保存账单。我希望它从后端和前端工作 这是我的账单模型: const mongoose = require("mongoose"); const { Schema } = mongoose; const billSchema = new Schema({ number: Number, date: { type: Date, default: Date.now() }, type: String, local: Str
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保存的,但实际输出是一条错误消息,提示“无法读取未定义的属性\u id”
有什么问题?错误消息,适用于哪一行代码_有几行提到了id属性。是。我只想从其他对象的关系中保存现有对象id,在这种情况下,bill是我要保存的对象,client和provider是我的关系。Bill对象具有类似于客户端和提供者的关系。在我的账单过账路径中,我想保存一张具有客户机id和提供者id的账单,如refs mongoose模式。我不知道如何在bill post路由中定义客户端id和提供者id。在控制台中,当您看到错误时,它会在发生此错误的位置写入行号。我想让你在你的问题中指出这条线。示例:错误发生在“let existingClient=wait Client.findById(Client.u id);”行。我相信是什么错误。我不会传递关系ID,比如post路由上的参数。从客户端,我可以使用window.location.replace函数,并指定要用来替换旧url的url