清理后无法将数据插入mongo集合

时间:2017-03-26 14:45:51

标签: node.js mongodb mongoose

我有点麻烦:我只是在我清理之后立即尝试将原始记录列表插入到mongodb集合中。但我没有收到insert方法的任何反馈。这是我的代码:

model.collection.remove((removeError, removeResult) => {
  console.log('remove cb');
  model.collection.insert(seeds, (insertError, insertedRecords) => {
    console.log('insert cb');
  });
});

实际上我想通过使用mongoose API(模型是猫鼬模型)来做到这一点,但在我探索这个问题的过程中,我发现原生驱动程序也没有执行它。

这就是我尝试使用mongoose包装器的原因:

model.remove({}, (err, docs) => {
    if (err) {
        console.log('remove error');
    } else {
        console.log('remove success');
        model.insertMany(seeds, (insertError, insertedRecords) => {
            if (insertError) {
                console.log('insert error');
            } else {
                console.log('insert success');
            }
        });
    }
});

当我运行此脚本时,我看到“删除成功”,这就是全部。如果我注释掉删除过程,则会显示“插入成功”

我的猫鼬模型非常简单:

const schema = new Schema({
   name: {type: String, unique: true, index: true},
});

seeds变量:

export default [
{name: 'USA'},
{name: 'Germany'},
{name: 'France'}, ...

请解释我错在哪里或我不明白

UPD

我使用MongoClient尝试了这个并且它有效!

MongoClient.connect(url, function(err, db) {
    const collection = db.collection('countries');
    collection.deleteMany({}, (err, r) => {
        console.log('delete', err);
        collection.insertMany(seeds, (err, r) => {
            console.log('insert', err);
            db.close();
            Country.find({}, function (err, res) {
                console.log(res);
            });
        });
    });
});

问题在于猫鼬。虽然实际上我认为{ModelName}.collection是本机驱动程序

1 个答案:

答案 0 :(得分:0)

要清除您的困惑,此行model.collection.remove((removeError, removeResult)是错误的。

删除的语法是db.collection.remove( <query>, <justOne> )

没有查询,但此处model.remove({}, (err, docs) => {您确实有查询({}),这意味着全部删除。

检查此语句db.mycol.remove({'title':'MongoDB Overview'}),这是查询和删除标题为MongoDB Overview的任何文档的查询。

这有什么意义吗?

相关问题