猫鼬无缘无故地返回空数组

时间:2019-02-25 21:41:50

标签: mongoose mongoose-populate

这太荒谬了。我已经在此处倾倒了文档和所有其他答案,并且没有理由不起作用。

型号:

import mongoose, { Schema } from 'mongoose';

const DriverSchema = new Schema({
  name: String,
  trips: [{ type: Schema.Types.ObjectId, ref: 'Trip' }],
});

export default mongoose.model('Driver', DriverSchema);
import mongoose, { Schema } from 'mongoose';

const TripSchema = new Schema({
  startTime: Date,
  endTime: Date,
  miles: Number,
  driver: {
    type: Schema.Types.ObjectId,
    ref: 'Driver',
  },
});

export default mongoose.model('Trip', TripSchema);

控制器:

export const getDriver = async (req, res) => {
  const { id } = req.params;
  try {
    const driver = await Driver.findById(id)
      .populate('trips')
      .exec();

    return res.json({
      driver,
      success: true,
    });
  } catch (error) {
    return res.json({ success: false, error });
  }
};

即使执行此操作也要获取一个空数组:

export const getDriver = async (req, res) => {
  const { id } = req.params;
  try {
    const driver = await Driver.findById(id);
    const { _id, name } = driver;
    const trips = await Trip.find({ driver: _id });
    return res.json({
      success: true,
      name,
      trips,
    });
  } catch (error) {
    return res.json({ success: false, error });
  }
};

所有数据返回

该哑人口函数有什么问题?

0 个答案:

没有答案