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

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

这抛出错误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)

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

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)


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

ckocjqey

ckocjqey1#

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

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

字符串

相关问题