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

wribegjk  于 2024-01-08  发布在  Go
关注(0)|答案(1)|浏览(186)

这抛出错误Station.UpdateMany不是一个函数,但在解析器上工作。

  1. const mongoose = require('mongoose')
  2. const Station = require('./Station')
  3. const customerSchema = mongoose.Schema({
  4. stations: [{
  5. type: mongoose.Schema.Types.ObjectId,
  6. ref: 'Station'
  7. }]
  8. })
  9. customerSchema.pre('save', async function() {
  10. await Station.updateMany( { _id:{ $in: this.stations } } ,{ $addToSet:{ customers: this._id } })
  11. })
  12. module.exports = mongoose.model('Customer', customerSchema)

字符串
关于Station Schema的类似作品

  1. const mongoose = require('mongoose')
  2. const uniqueValidator = require('mongoose-unique-validator')
  3. const Customer = require('./Customer')
  4. const stationSchema = new mongoose.Schema({
  5. customers: [{
  6. type: mongoose.Schema.Types.ObjectId,
  7. ref: 'Customer'
  8. }]
  9. })
  10. stationSchema.plugin(uniqueValidator)
  11. stationSchema.pre('save',async function() {
  12. await Customer.updateMany({ _id:{ $in: this.customers } }, { $addToSet:{ stations: this._id } })
  13. })
  14. module.exports = mongoose.model('Station',stationSchema)


不知道为什么一个工作,而不是其他?

ckocjqey

ckocjqey1#

最后弄明白了,这个问题是因为循环依赖Station => Customer => Station。我通过在pre钩子中导入Model而不是从Station和Customer开始解决了这个问题。希望这能帮助到一些人。

  1. customerSchema.pre('save', async function() {
  2. const Station = require('./Station')
  3. await Station.updateMany( { _id:{ $in: this.stations } } ,{ $addToSet:{ customers: this._id } })
  4. })

字符串

相关问题