【问题标题】:Populate returns whole parent document填充返回整个父文档
【发布时间】:2020-12-05 18:19:13
【问题描述】:

我刚开始学习 express 和 mongodb。我最近遇到了这种问题,我正在尝试选择 Room 模型内的所有子文档。

const books = await Room.find().populate('book');

但当我只想选择 bookings 字段时,它会返回整个房间文档。

这是图书架构

const bookSchema = new mongoose.Schema({
  startDate: {
    type: Date,
    required: true,
  },
  endDate: {
    type: Date,
    required: true,
  },
  name: {
    type: String,
    required: true,
  },
  phone: {
    type: String,
    required: true,
  },
});

module.exports = mongoose.model("book", bookSchema)

这是房间架构

const roomSchema = new mongoose.Schema({
  currentlyReserved: {
    type: Boolean,
    default: false,
  },
  people: {
    type: Number,
    required: true,
  },
  roomNumber: {
    type: Number,
    required: true,
  },
  pricePerPerson: {
    type: Number,
    required: true,
  },
  reservedUntil: {
    type: Date,
    default: null,
  },
  reservedBy: {
    type: String,
    default: null,
  },
  bookings: {
    type: [{ type: mongoose.Schema.Types.ObjectId, ref: "book" }],
  },
});

module.exports = mongoose.model("room", roomSchema);

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    您可以使用第二个 arg 进行投影到 find()。

    https://docs.mongodb.com/manual/reference/method/db.collection.find/#projection

    const books = await Room.find({}, {bookings: 1}).populate('bookings');
    

    【讨论】:

      猜你喜欢
      • 2016-01-21
      • 1970-01-01
      • 2019-06-28
      • 2014-11-20
      • 2013-06-30
      • 1970-01-01
      • 2017-04-06
      • 2019-08-04
      • 2012-08-14
      相关资源
      最近更新 更多