【问题标题】:Mongoose populate returns empty array or list of ObjectIdsMongoose 填充返回空数组或 ObjectIds 列表
【发布时间】:2021-01-08 19:32:58
【问题描述】:

我正在通过构建关系 API 来练习我的 express.js 技能,并且正在努力在模式中填充键。

我正在构建它,因此我有一个属性列表,并且这些属性具有单位。这些单位有一个 propertyId 键。

这当前返回一个空数组,而如果我删除 populate({}) 它返回一个 ObjectIds 数组。

我已经阅读了许多帖子,有些人通过使用 .populate({path: 'path', model: Model}); 解决了这个问题。但这似乎没有奏效。我认为这可能是我向单元添加 propertyId 的方式,但我不确定。谁能看到我哪里出错了?任何帮助将不胜感激。

这是架构。

属性:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const PropertySchema = new Schema({
  title: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  },
  units: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'unit'
    }
  ]
});

module.exports = Property = mongoose.model('property', PropertySchema);

单位:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const UnitSchema = new Schema({
  title: {
    type: String,
    required: true
  },
  propertyId: {
    type: Schema.Types.ObjectId,
    ref: 'property'
  }
});

module.exports = Unit = mongoose.model('unit', UnitSchema);

然后我创建这样的单元:

-- api/properties/:id/units --
router.post('/:id/units', async (req, res) => {

  // Get fields from req.body
  const { title } = req.body;

  // Get current property
  const property = await Property.findById(req.params.id);

  try {

    // Throw error if no property
    if (!property) {
      return res.status(400).json({ msg: 'Property not found' });
    }

    // Create new unit
    const newUnit = new Unit({
      title,
      propertyId: req.params.id
    });

    // Add new unit to property's units array
    property.units.unshift(newUnit);

    // Save property
    await property.save();

    // Return successful response
    return res.status(200).json(property);

  } catch (error) {
    console.error(error.message);
    return res.status(500).send('Server error');
  }
});

并尝试填充 GET 请求

-- /api/properties/:id/units --
const Unit = require('../../models/Unit');

router.get('/:id/units', async (req, res) => {
  const property = await Property.findOne({ _id: req.params.id }).populate({path: 'units', model: Unit});
  const propertyUnits = property.units;
  return res.status(200).json(propertyUnits);
});

如果我删除 .populate({path: 'units', model: Unit});,我会得到一个单元 ID 列表,如下所示:

[
    "5ff7256cda2f5bfc1d2b9108",
    "5ff72507acf9b6fb89f0fa4e",
    "5ff724e41393c7fb5a667dc8",
    "5ff721f35c73daf6d0cb5eff",
    "5ff721eb5c73daf6d0cb5efe",
    "5ff7215332d302f5ffa67413"
]

【问题讨论】:

    标签: javascript node.js express mongoose mongoose-schema


    【解决方案1】:

    我不知道,你为什么不这样尝试:

    await Property.findOne({ _id: req.params.id }).populate('units')
    

    我已经尝试过上面的代码并且它正在工作。

    注意:确保检查您的 req.params.id 不为空或未定义,并确保您找到的数据在您的 mongodb 中不为空。

    更新:我一直在尝试您的代码,它运行良好。

    【讨论】:

    • 如果我只使用 .populate('units') 它返回一个空数组。它的工作原理是将单位保存到属性中,但不使用 Unit 对象填充属性。在我的数据库中,我目前只有一个 ObjectIds 数组。
    • 没错,它还在工作。如果你需要截图,我可以添加。
    • 它仍然只为我显示 ObjectId。你能添加一个显示属性内单元对象的屏幕截图吗?
    【解决方案2】:

    此问题是由于命名不一致以及未保存新创建的单元以及更新的属性造成的。

    我仔细检查了我的所有架构导出和引用,并注意到我在某些情况下使用大写字母,在其他情况下使用小写字母,并在 POST 请求中保存了 newUnit 以及更新的属性并且它起作用了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-18
      • 2016-12-04
      • 1970-01-01
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      • 2020-11-11
      • 2019-02-13
      相关资源
      最近更新 更多