This throws error Station.UpdateMany is not a function but works when on resolver.
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)
Similar works on 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)
No Idea why one works and not other?
Finally figured it out, the issue was because of cyclic dependency Station => Customer => Station. I solved it by importing the Model inside the pre hook instead of beginning on both Station and Customer. Hope this will help somebody.
customerSchema.pre('save', async function() {
const Station = require('./Station')
await Station.updateMany( { _id:{ $in: this.stations } } ,{ $addToSet:{ customers: this._id } })
})