简体   繁体   中英

how does “insertMany” work with Mongoose when using Node.js with mongoDB?

I am learning Node.js and am trying to work with mongo db and am using mongoose. I am detecting a pattern with insertMany that doesn't make sense to me in the below code

  ItemsModel.find({}, function(err, toDoListDb) {
  if (err) {
    console.log("error reading items");
  } else {
    console.log("the DB length is " + toDoListDb.length);
    if (toDoListDb.length === 0) {
      ItemsModel.insertMany(defaultItems, function(err) {
        if (err) {
          console.log("Error while inserting default items");
        } else {
          console.log("default items insertion successful");
        }
      });
      console.log("entered default items and redirect");

      res.redirect("/");
    } else {
      console.log("read from DB successful");
      res.render("list", {
        listTitle: day,
        newListItems: toDoListDb
      });
    }
  };
});

I have an array (outside this code) that has a list of "default items" to write to the database, if the first time i hit localhost upon running the application, and the database is empty. I check the length of database collection, and if it is 0, the default items are written to the database. If the DB already has some documents, that it passes it to an ejs template and renders it.

I have the console.logs to analyse what happens when the db is initially empty. if the database is absolutely empty - no collections defined inside. Then, for some reason the code takes multiple attempts to write to the database. On the last attempt, when the db write actually succeeds, I actually get both the console logs: "default items insertion successful" and "error while inserting default items", in that order. That makes no sense.

I am testing this by running the app after doing a dropDatabase() at the mongoDB console. If instead of dropDatabase, I just delete the documents in the collection, but retain the empty collection inside the DB, the insertMany for default items works as expected.

So my question is, is there a way to understand what happens inside insertMany and be confident about whatever happens in the back end. Because I am seeing several questions here about insertMany not inserting items as expected.

PS: The final output that gets rendered is correct. I am just not clear about how the DB write is executed.

I would say most issues are due to people misunderstanding how node works and specifically asynchronous programming, callbacks, promises and async/await. The consequence is inserting multiple times when people expect one insert or executing operations concurrently when they think they are writing sequential code, etc.

My suggestion is to carefully follow official documentation. It is unlikely that the issue is in the driver or the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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