如何在我的场景中实现 Mongoose Populate?

问题描述 投票:0回答:1

我对使用 Mongoose 中的填充功能相对较新。我需要用该客户的订单列表填充“客户”模型的“_id”字段。这是架构。

Customer_Schema = {
 name : string,
 phone : string,
 email : string

Orders_Schema= {
 customerID : string,  // This is the object ID of the customer from the "Customer_Schema"
 phone : string,
 email : string

现在我想知道如何在模式中设置“refs”以及如何执行填充命令。对于我的最终结果,我希望获得客户的“customerID”下的所有订单数据。

谢谢。

node.js mongodb mongoose mongoose-populate
1个回答
0
投票

您可以在 orderSchema 中设置指向“Customer”模型的引用。

// Customer Schema
const customerSchema = new mongoose.Schema({
  name: String,
  phone: String,
  email: String
})
// Order Schema
const orderSchema = new mongoose.Schema({
  customerID: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Customer' // Reference to the Customer model
  },
  phone: String,
  email: String
})
// Define the models. Export models if necessary...
const Customer = mongoose.model('Customer', customerSchema)
const Order = mongoose.model('Order', orderSchema)

现在您可以使用 populate 来获取客户和订单,

Customer.findOne({ /* your query criteria .... */ })
  .populate('customerID') // 'customerID' should match the field name in the orderSchema
  .exec((err, customerWithOrders) => {
    if (err) {
      console.error(err)
      return
    }

    console.log('Customer with orders:', customerWithOrders)
  })
© www.soinside.com 2019 - 2024. All rights reserved.