简体   繁体   English

将文档插入数据库之前,MongoDB空集合

[英]MongoDB empty collection before insert document into db

I'm trying to implement a function to empty the collection every time I populate document into the database. 我正在尝试实现每次将文档填充到数据库中时都清空集合的功能。 This doesn't work for me. 这对我不起作用。 I also tried using async.series , but still no luck. 我也尝试使用async.series ,但还是没有运气。 Why doesn't this code below work? 为什么下面的代码不起作用? The output always with db.users.find().count() gave me 0 . 始终带有db.users.find().count()的输出给了我0

function emptyThenInsert(db) {
  UserSchema.collection.remove({}, function(err) {
    if(err) console.log(err);
    UserSchema.collection.insert(db, function(err, data) {
      console.log(data);
      if (err) console.log(err);
      UserSchema.collection.find({}, function(err, data) {
        console.log(data);
        if (err) console.log(err);
      });
    });
  });
}

It works if I take out UserSchema.collection.remove . 如果我取出UserSchema.collection.remove

This seem to work for me. 这似乎对我有用。

function emptyThenInsert(db) {
  UserSchema.remove({}, function(err) {
    if(err) console.log(err);
    UserSchema.collection.insert(db, function(err, data) {
      if (err) console.log(err);
      UserSchema.collection.find({}, function(err, data) {
        if (err) console.log(err);
      });
      process.exit(1);
    });
  });
}

尝试使用写关注点:

UserSchema.collection.insert(db, {w:1}, function(err, data) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM