2017-03-26 29 views
0

我有点麻烦:我只是试图在清理完成后将原始记录列表插入到mongodb集合中。但我没有收到任何来自insert方法的反馈。这是我的代码:清理后无法将数据插入到mongo集合中

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

其实我想用猫鼬API(模型是猫鼬模型),但在我的探索这个问题的办法做到这一点,我想通了,本地驱动程序不执行此以及。

这就是我一直试图用猫鼬包装:

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是本机驱动

回答

0

要清除你的困惑,这条线model.collection.remove((removeError, removeResult)是错误的。

用于去除语法是这样的,db.collection.remove( <query>, <justOne> )

没有查询,但在这里model.remove({}, (err, docs) => {你有查询({}),这意味着全部删除。

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

这是否有任何意义?

+0

据我所知'删除'方法从收集丢弃记录,而不是收集本身 –

+0

检查更新的答案。 – Remario

+0

我已经尝试了两种变体,结果是一样的 –

相关问题