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

后端 未结 6 1845
太阳男子
太阳男子 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:40

    This is because require one Model in two paths.

    // Comment Model file

    var mongoose = require('mongoose')
    var Schema = mongoose.Schema
    
    var CommentSchema = Schema({
      text: String,
      author: String
    })
    
    module.exports = mongoose.model('Comment', CommentSchema)
    

    // Seed file

    const commentData = {
      user: "David Lee",
      text: "This is one comment"
    }
    var Comment = require('./models/Comment')
    
    module.exports = function seedDB () {
      Comment.create(commentData, function (err, comment) {
        console.log(err, commemt)
      })
    }
    

    // index file

    var Comment = require('./models/comment')
    var seedDB = require('./seeds')
    seedDB()
    const comment = {
      text: 'This girl is pretty!',
      author: 'David'
    }
    Comment.create(, function (err, comment) {
        console.log(err, comment)
     })
    

    Now you will get throw new mongoose.Error.OverwriteModelError(name), Cuz you require Comment model in two different ways. Seed file var Comment = require('./models/Comment'),Index file var Comment = require('./models/comment')

提交回复
热议问题