尝试在Mongoose 7中使用“虚拟填充”,但无法Map任何数据

nzkunb0c  于 2023-08-06  发布在  Go
关注(0)|答案(1)|浏览(82)

我在Express.js中使用Mongoose.js,并尝试使用“虚拟填充”功能。
我有两个集合,分别是“房间”和“订单”,它们的定义就像下面的代码一样。

const RoomSchema = new mongoose.Schema(
  {
    title: {
      type: String,
      required: true,
    }
    roomNumbers: [
      {
        number: Number
      },
    ],
  }
);
export default mongoose.model("Room", RoomSchema);

const OrderSchema = new mongoose.Schema(
  {
    userId: { type: String, required: true }, 
    roomNumberId: [
      {
        type: mongoose.Types.ObjectId,
        ref: "Room",
      },
    ]   
  },
  {
    toObject: {
      virtuals: true,
    },
    toJSON: {
      virtuals: true,
    },
  }
);
OrderSchema.virtual("roomNumberList", {
  ref: "Room",
  localField: "roomNumberId", 
  foreignField: "roomNumbers",
});
export default mongoose.model("Order", OrderSchema);

字符串
我的目标是使用Order集合的userId,填充Room集合的roomNumbersname。所以,我访问数据的过程是:

export const getAllOrdersByUserId = async (req, res, next) => {
  const userId = req.params.id;
  try {
    const ordersList = await Order.find({ userId: userId })
      .populate("roomNumberList") 
      .exec();
    console.log(ordersList);
    res.status(200).json(ordersList);
  } catch (error) {
    next(errorMessage(500, "Server error", error));
  }
}


json的结果是:

{
    _id: new ObjectId("64b70c60d6048e2881099496"),
    userId: '6478efd33cc47792f3ce6bc9',
    roomNumberId: [
      new ObjectId("6495c7caef3162cf3e2634bd"),
      new ObjectId("6495c7d3ef3162cf3e2634c2"),
      new ObjectId("6495c7d7ef3162cf3e2634c7")
    ],
    createdAt: 2023-07-18T22:04:16.178Z,
    updatedAt: 2023-07-18T22:04:16.178Z,
    __v: 0,
    roomNumberList: [],
    id: '64b70c60d6048e2881099496'
  }


result json的roomNumberList部分为空....
我花了几天时间寻找可能的答案,但没有找到。
请大家帮忙给予一些想法。- 谢谢-谢谢

jexiocij

jexiocij1#

我终于想通了。
首先,我添加了“mongoose debug”设置,用于显示MongoDB如何工作的细节,如

mongoose.set("debug", (collectionName, method, query, doc) => {
  console.log(`${collectionName}.${method}`, JSON.stringify(query), doc);
});

字符串
然后我发现MongoDB没有使用Room集合的roomNumbers._idMapOrder集合。
所以,我将我的foreignField改为foreignField:“roomNumbers._id”,喜欢

OrderSchema.virtual("roomNumberList", {
  ref: "Room",
  localField: "roomNumberId", //It is any field of the current collection.
  foreignField: "roomNumbers._id", //It is any field of the collection from which we want to populate the document.
});

相关问题