首页 > 解决方案 > 在 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”

怎么了?

标签: node.jsmongoose

解决方案


推荐阅读