'Mongoose deleteMany() is deleting a future create()

Here is my full script:

import path from 'path'
import mongoose from 'mongoose'
import dotenv from 'dotenv'
import { SiteConfigModel } from '../src/feature/site-config/model'
import { siteConfigData } from '../data/siteConfigData'
import { UserModel } from '../src/auth/model/UserModel'
import { userData } from '../data/userData'

const configPath = path.join(__dirname, '..', '.env.local')
dotenv.config({ path: configPath })

const MONGO_URI = process.env.MONGO_URI || 'MISSING'

console.log(`Using mongo URI: ${MONGO_URI}`)

const mongoConnect = async () => {
  console.log('Attempting mongo connection...')
  const {
    connection: { host },
  } = await mongoose.connect(MONGO_URI)
  console.log(`MongoDB Connected: ${host}`)
}

const importSiteConfig = async () => {
  try {
    await SiteConfigModel.deleteMany()
    await SiteConfigModel.create(siteConfigData)
    console.log('Data imported!')
    process.exit(0)
  } catch (error) {
    console.error(error)
    process.exit(1)
  }
}

const importUsers = async () => {
  try {
    await UserModel.deleteMany()
    await UserModel.create(userData)
  } catch (error) {
    console.error(error)
    process.exit(1)
  }
}

mongoConnect()
importSiteConfig()
importUsers()

When I run it with ts-node ./scripts/seeder.ts the users collection is empty. However, if I make a small modification:

    const importUsers = async () => {
      try {
        // await UserModel.deleteMany()  // DELETE THIS LINE
        await UserModel.create(userData)
      } catch (error) {
        console.error(error)
        process.exit(1)
      }
    }

Then there are two records in the database.

I am not expecting this result, because the deleteMany() is coming before the create(). How come this is occuring?



Solution 1:[1]

try this:

const importSiteConfig = async () => {
  try {
    await SiteConfigModel.deleteMany()
    await SiteConfigModel.create(siteConfigData)
    console.log('Data imported!')
  } catch (error) {
    console.error(error) // or throw error
  }
}

const importUsers = async () => {
  try {
    await UserModel.deleteMany()
    await UserModel.create(userData)
  } catch (error) {
    console.error(error) // or throw error
  }
}


(async()=> {
   try{
      await mongoConnect()
      await importSiteConfig()
      await importUsers()
      process.exit(0)
   }catch(e){
      process.exit(1)
   }
})()

Updated:

As I Test in my environment:

Project structure:

enter image description here

In my node.ts I have the following:

const mongoose = require("mongoose");
const { Schema } = mongoose;

const SiteConfigSchema = new Schema({
  config1: Boolean,
  config2: Boolean,
});

const UserModelShema = new Schema({
  name: String,
});

const configModel = mongoose.model("config", SiteConfigSchema);
const userModel = mongoose.model("user", UserModelShema);

const mongoConnect = async () => {
  console.log("Attempting mongo connection...");
  const {
    connection: { host },
  } = await mongoose.connect(`mongodb://localhost:27017/testdb`);
  console.log(`MongoDB Connected: ${host}`);
};

const importSiteConfig = async () => {
  try {
    await configModel.deleteMany();
    await configModel.create({ config1: true, config2: false });
    console.log("config Data imported!");

  } catch (error) {
    console.error(error); // or throw error
  }
};

const importUsers = async () => {
  try {
    await userModel.deleteMany();
    await userModel.create([{ name: "user 1" }, { name: "user 2" }]);

   console.log("user Data imported!");
  } catch (error) {
    console.error(error); // or throw error
  }
};

(async () => {
  try {
    await mongoConnect();
    await importSiteConfig();
    await importUsers();
    process.exit(0);
  } catch (e) {
    process.exit(1);
  }
})();

package.json:

{
  "name": "test",
  "version": "1.0.0",
  "main": "node.ts",
  "license": "MIT",

  "scripts": {
    "seeder": "npx ts-node node.ts"
  },
  "dependencies": {
    "mongoose": "^6.3.0",
    "typescript": "^4.6.3"
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1