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

ff29svar  于 5个月前  发布在  Go
关注(0)|答案(1)|浏览(55)

我对使用Mongoose中的populate特性比较陌生。我需要用这个客户所做的Orders列表来填充我的“Customer”模型的“_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”以及如何执行populate命令。对于我的最终结果,我想得到客户的“customerID”下的所有订单数据。
谢谢.

jtw3ybtb

jtw3ybtb1#

您可以在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)
  })

相关问题