mongoose踩坑笔记: Cannot overwrite `` model once compiled.

出现这个问题是因为

var schema = new mongoose.Schema({
    qishu: Number,
    shengliguojia: Number
});
var temp = mongoose.model('yulechang', schema, 'yulechang');

重复定义‘mongoose.model(‘yulechang’, schema, ‘yulechang’)’这个,写一遍就行(下面是示例:这是改过后的)

var schema = new mongoose.Schema({
    qishu: Number,
    shengliguojia: Number
});
var temp = mongoose.model('yulechang', schema, 'yulechang');
mongoose.connect(db_str, {
    useNewUrlParser: true
}, function(err) {
    if (!err) {
        temp.find().sort({
            "qishu": -1
        }).exec(function(err, docs) {
            console.log(docs);
            if(docs.length = 0){
                 qishu = docs[0].qishu;
            }
        });
    }
});
setInterval(() => {
    if (countOfYulechang >= 6) {
        qishu=qishu+1;
        let shengliguojia= Math.floor( Math.random()*3 )+1;
        mongoose.connect(db_str,{ useNewUrlParser: true }, function(err) {
            if (!err) {
                temp.insertMany([{
                    qishu: qishu,
                    shengliguojia:shengliguojia
                }], function(err, docs) {
                    console.log(docs);
                });
            }
        });
        countOfYulechang = 0
    } else {
        countOfYulechang = countOfYulechang + 1
    }
}, 1000)

下面是修改之前的

mongoose.connect(db_str, {
    useNewUrlParser: true
}, function(err) {
    if (!err) {
        var schema = new mongoose.Schema({
            qishu: Number,
            shengliguojia: Number
        });
        var temp = mongoose.model('yulechang', schema, 'yulechang');
        temp.find().sort({
            "qishu": -1
        }).exec(function(err, docs) {
            console.log(docs);
            if(docs.length = 0){
                 qishu = docs[0].qishu;
            }
        });
    }
});
setInterval(() => {
    if (countOfYulechang >= 6) {
        qishu=qishu+1;
        let shengliguojia= Math.floor( Math.random()*3 )+1;
        mongoose.connect(db_str,{ useNewUrlParser: true }, function(err) {
            if (!err) {
                var schema = new mongoose.Schema({
                    qishu: Number,
                    shengliguojia: Number
                });
                var temp = mongoose.model('yulechang', schema, 'yulechang');
                temp.insertMany([{
                    qishu: qishu,
                    shengliguojia:shengliguojia
                }], function(err, docs) {
                    console.log(docs);
                });
            }
        });
        countOfYulechang = 0
    } else {
        countOfYulechang = countOfYulechang + 1
    }
}, 1000)
    原文作者:弱鸡的前端程序员
    原文地址: https://segmentfault.com/a/1190000019201081
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞