提问者:小点点

填充返回整个父文档


我刚开始学习express和MongoDB。我最近遇到了这样的问题,我试图选择rooy模型中的所有子文档。

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);


共1个答案

匿名用户

您可以通过两种方式从房间集合中仅选择预订字段。

>

  • 使用select方法

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

    将投影对象传递给.find()方法

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

    有关详细信息,请参阅:

    • Query.Prototype.Select()
    • db.collection.find()-projection

    p.s:您正在将集合的名称(book)传递给.populate()方法,而应该传递要填充的字段的名称,在您的示例中是bookings

    更改

    .populate('book');
    

    .populate('bookings');