Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

node.js - How to populate in this kind of situation?

I am trying to draw out the data of services name from the income.

My income model is like this

const IncomeSchema = new mongoose.Schema(
  {
    shop_id: { type: mongoose.Schema.Types.ObjectId, ref: "Shop" },
    services: [
      {
        service_id: { type: mongoose.Schema.Types.ObjectId, ref: "Service" },
        price: { type: Number },
      },
    ]
    total_amount: { type: Number, required: true },
  },
  {
    timestamps: true,
  }
);

As you can see I made services an array of services-id,

What I am doing now is i am write a get route for every single income. I want to return the already populated data for services. But something wrong with my populate method.

Here is the get route.

router
  .route("/:income_id")
  .get((req, res) => {
      Income.findById(req.params.income_id).populate('services')
        .then((income) => {
          res.json(income);
        })
        .catch(function (error) {
          res.status(404).json({ msg: "Income not Found" });
        });
  });

Above here i try to populate the services but I am not getting the populate result. Here is the result

{
    "_id": "600edf419340741fd454a391",
    "services": [
        {
            "_id": "600edf419340741fd454a392",
            "service_id": "600c5fdeef955d5794465bbd",
            "price": 4000
        },
        {
            "_id": "600edf419340741fd454a393",
            "service_id": "600c5fb6ef955d5794465bbc",
            "price": 5000
        }
    ],
    "total_amount": 9000,
    "shop_id": "600c5d505938a420fc27c90b",
    "createdAt": "2021-01-25T15:09:53.329Z",
    "updatedAt": "2021-01-25T15:09:53.329Z",
    "__v": 0
}
question from:https://stackoverflow.com/questions/65887866/how-to-populate-in-this-kind-of-situation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...