首页 > 解决方案 > 如何在猫鼬/节点 JS 中解决这个引用问题

问题描述

我有用户的路线和模型,然后是贷款的另一个。我试图在 Loan 路由中引用用户,但每当我在 PostMan 上测试时都会收到此错误:

TypeError: Cannot read property '_id' of undefined
    at C:\Users\Micho\Documents\GBENGA\BE\src\routes\loans\index.js:38:47

贷款模型代码为:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;


const loanSchema = new Schema({
    customerName: {
        type: String,
        required: true
    },
    gender: {
        type: String
    },
    address: {
        city: String,
        state: String,
    },
    amount: {
        type: Number
    },
    loanTenure: {
        type: Number
    },
    user: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    loanStatus: {
        type: String,
        default: "created"
    }
}, {
    timestamps: true
})

我的路线是这样的:

router.post("/", async (req, res) => {
    try {

      let loan = await new Loan({...req.body});

      loan.save();

        await User.findByIdAndUpdate(req.user._id, { $push: { loans: loan._id } })
        console.log(req.user)

      loan = await Loan.findById(loan._id).populate("user");
      res.send(loan);
    } catch (error) {
        console.log(error)
      res.status(500).send(error);
    }
  });

请帮忙。谢谢

标签: javascriptnode.jsmongodbmongoosepostman

解决方案


推荐阅读