首页 > 解决方案 > 如何发布和填写账单

问题描述

我在比尔的模型中有一个名为“客户端”的关系 json。这是我的代码:

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", required: true },
  detail: [
    {
      quantity: Number,
      product: { code: Number, name: String, price: Number },
      undertotal: Number
    }
  ],
  total: Number
});

mongoose.model("bills", billSchema);

这是我的发帖路线:

app.post("/api/bills", async (req, res) => {
  const { number, type, local, client, detail, total } = req.body;

  await Client.findById(req.body.client._id).then(client => {
    if (!client) {
      return res.status(404).json({
        message: "client not found"
      });
    }
  });

  const bill = new Bill({
    number,
    date: new Date(),
    type,
    local,
    client,
    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);
    }

    res.status(500).send(err);
  }
});

//my get route

app.get("/api/bills", function(req, res) {
  Bill.find({}, function(err, bills) {
    Client.populate(bills, { path: "clients" }, function(err, bills) {
      res.status(200).send(bills);
    });
  });
});

我想要这样的东西:

{
    "number": 302,
    "type": "c",
    "local": "porstmouth",
    "client": {
        "address": {
            "street": "victoria street",
            "number": 1001,
            "floor": "2",
            "flat": 4
        },
        "_id": "5dab929613fb682b48e4ca6b",
        "name": "luke skywalker",
        "mail": "l.skywalker@yahoo.com",
        "cuil": "39193219",
        "phone": 128391,
        "__v": 0
    },
    "detail": [
        {
            "quantity": 500,
            "product": {
                "code": 300,
                "name": "P2",
                "price": 800
            },
            "undertotal": 5000
        }
    ],
    "total": 11000
}

但我看到了这个结果:

{
    "date": "2019-10-20T12:27:17.162Z",
    "_id": "5dac52a577e09b4acc45718d",
    "number": 302,
    "type": "c",
    "local": "porstmouth ",
    "client": "5dab929613fb682b48e4ca6b",
    "detail": [
        {
            "_id": "5dac52a577e09b4acc45718e",
            "quantity": 500,
            "product": {
                "code": 300,
                "name": "P2",
                "price": 800
            },
            "undertotal": 5000
        }
    ],
    "total": 11000,
    "__v": 0
}

我不想只看到 id 客户端。我想查看账单中客户的所有内容。我尝试使用填充方法,但没有结果。

那么,在这种情况下,发布和填充嵌套 json 关系对象的形式是什么?

标签: node.jsmongoose

解决方案


虽然只发布 clientId 就足够了。

所以你的发布路线可以是这样的(你都使用了等待,然后,这是不正确的,所以我将它重构为只使用等待)

app.post('/api/bills', async (req, res) => {

  const { number, type, local, client, detail, total } = req.body;

  let existingClient = await Client.findById(req.body.client._id)

  if (!existingClient) {
    return res.status(404).json({
      message: "client not found"
    });
  }

  const bill = new Bill({
    number,
    date: new Date(),
    type,
    local,
    client: req.body.client._id
    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);
    }

    res.status(500).send(err);
  }
});

在获取所有客户端信息的获取路径中,您需要像这样填充它:

app.get('/api/bills', async (req, res) => {

  try {
    const bills = await Bill.find({}).populate("clients");

    res.status(200).send(bills);
  } catch (err) {
    console.log(err);
    res.status(500).send(err);
  }
}
)


推荐阅读