Mongoose Model.UpdateMany 不是预挂钩上的函数错误,这适用于类似的模式和解析器

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

这会引发错误 Station.UpdateMany 不是函数,但在解析器上有效。

const mongoose = require('mongoose')
const Station = require('./Station')

const customerSchema = mongoose.Schema({
  stations: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Station'
  }]
 })

customerSchema.pre('save', async function() {
  await Station.updateMany( { _id:{ $in: this.stations } } ,{ $addToSet:{ customers: this._id } })
})    

module.exports = mongoose.model('Customer', customerSchema)

车站架构上的类似工作

const mongoose = require('mongoose')
const uniqueValidator = require('mongoose-unique-validator')
const Customer = require('./Customer')

const stationSchema = new mongoose.Schema({
  customers: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Customer'
  }]
})

stationSchema.plugin(uniqueValidator)

stationSchema.pre('save',async function() {
  await Customer.updateMany({ _id:{ $in: this.customers } }, { $addToSet:{ stations: this._id } })
})

module.exports =  mongoose.model('Station',stationSchema)

不知道为什么一个有效而另一个无效?

mongodb mongoose mongoose-schema
1个回答
1
投票

终于弄清楚了,问题是因为循环依赖Station => Customer => Station。我通过在 pre hook 中导入模型来解决这个问题,而不是从 Station 和 Customer 上开始。希望这会对某人有所帮助。

   customerSchema.pre('save', async function() {
      const Station = require('./Station')
      await Station.updateMany( { _id:{ $in: this.stations } } ,{ $addToSet:{ customers: this._id } })
    })  
© www.soinside.com 2019 - 2024. All rights reserved.