mongoose create function in not function error(sub document)

261 views Asked by At

schema

const UserSchema = new mongoose.Schema({
...,
  suported: [{name:String, id:String}],
  suporting: [{name:String, id:String}]

},
  { timestamps: true });

Query

const requester = await User.findOne({ _id }) 
const suporter = await User.findOne({ _id: _idSuporter })
        // Result ok
         requester.suported.create(data); // causing error
          suporter.suporting.create(data); 

Error message: requester.suported.create is not a function.

Edited Links to where you can see what I am expecting

  1. https://mongoosejs.com/docs/subdocs.html#adding-subdocs-to-arrays

  2. https://attacomsian.com/blog/mongoose-subdocuments

1

There are 1 answers

4
Maykon Meneghel On

The error is happening because it is not possible to call the create function on the "supported" attribute of the User object. What you can do is create a static function that takes the data as a parameter and does something when the function is called, like this:

userSchema.statics.createSupported = function(data: any) {
     // do something here..
}

userSchema.statics.createSupporting = function(data: any) {
     // do something here..
}

And when you call the query:

const requester = await User.findOne({ _id })
const supporter = await User.findOne({ _id: _idSuporter })
// Result ok
User.createSupported(date)
User.createSupporting(data)