How to get rid of Error: “OverwriteModelError: Cannot overwrite `undefined` model once compiled.”?

后端 未结 6 1830
太阳男子
太阳男子 2021-02-05 07:34

I have a common method for updating document of any collection in MongoDB?

The following code is in file name Deleter.js

module.exports         


        
6条回答
  •  日久生厌
    2021-02-05 08:16

    I try to avoid globals as much as possible, since everything is by reference, and things can get messy. My solution

    model.js

      try {
        if (mongoose.model('collectionName')) return mongoose.model('collectionName');
      } catch(e) {
        if (e.name === 'MissingSchemaError') {
           var schema = new mongoose.Schema({ name: 'abc });
           return mongoose.model('collectionName', schema);
        }
      }
    

提交回复
热议问题