Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Web Development
  3. ASP.NET
  4. .Net Core 2.1, seeding a MongoDB, foreach on Countries,

.Net Core 2.1, seeding a MongoDB, foreach on Countries,

Scheduled Pinned Locked Moved ASP.NET
csharpjavascriptasp-netmongodbdotnet
3 Posts 1 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J Offline
    J Offline
    jkirkerx
    wrote on last edited by
    #1

    It's been pretty rough trying to figure out how to write the MongoDB context and some sort of MongoInitializer that runs from Programs.cs while passing the settings to load the MongoDB parameters. I'm seeding in .Net Core and not Angular V6 because it just seems like the right place to do it. So I've seeded my default users, countries, and now states / provinces. I decided to copy the format of my previous versions here, but was forced to really change it up MongoDB style. I'm trying to loop through the countries I just wrote, to create states. So this is what I wrote based off research from the internet. Don't know if it's right or wrong and it's very foreign to me. I'm in uncharted waters here on this. I understand this: var websiteCountries = _database.GetCollection("Website_Countries"); but not the cursor part: using (IAsyncCursor cursor = await websiteCountries.FindAsync(new BsonDocument())) So the above code must set the cursor position; perhaps it set it at the end, and that's why the batch is null. I'm not even sure if I'm on the right track here. I really don't care if it's async or not. I'll read up on this part here await websiteCountries.FindAsync(new BsonDocument())

    public static async Task SeedAsync(IMongoDatabase _database)
    {
    var websiteStates = _database.GetCollection<WEBSITE_STATES>("Website_States");

    // Check and see if we have any website users
    double totalDocuments = websiteStates.CountDocuments(FilterDefinition<WEBSITE\_STATES>.Empty);
    if (totalDocuments == 0)
    {
    
        var websiteCountries = \_database.GetCollection<WEBSITE\_COUNTRIES>("Website\_Countries");
    
        try
        {
            using (IAsyncCursor<WEBSITE\_COUNTRIES> cursor = await websiteCountries.FindAsync(new BsonDocument()))
            {
                IEnumerable<WEBSITE\_COUNTRIES> batch = cursor.Current; // batch is null here
                foreach (WEBSITE\_COUNTRIES country in batch)
                {
                    Console.WriteLine(country.LongName);
                }
            }
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message.ToString());
        }                
    }            
    

    }

    I wrote this, well sort of copied it, havn't tested it yet. This is in my UserRespository and according to documentation is a CRUD method of getting all the users. What's sort of confusing is the context

    J 1 Reply Last reply
    0
    • J jkirkerx

      It's been pretty rough trying to figure out how to write the MongoDB context and some sort of MongoInitializer that runs from Programs.cs while passing the settings to load the MongoDB parameters. I'm seeding in .Net Core and not Angular V6 because it just seems like the right place to do it. So I've seeded my default users, countries, and now states / provinces. I decided to copy the format of my previous versions here, but was forced to really change it up MongoDB style. I'm trying to loop through the countries I just wrote, to create states. So this is what I wrote based off research from the internet. Don't know if it's right or wrong and it's very foreign to me. I'm in uncharted waters here on this. I understand this: var websiteCountries = _database.GetCollection("Website_Countries"); but not the cursor part: using (IAsyncCursor cursor = await websiteCountries.FindAsync(new BsonDocument())) So the above code must set the cursor position; perhaps it set it at the end, and that's why the batch is null. I'm not even sure if I'm on the right track here. I really don't care if it's async or not. I'll read up on this part here await websiteCountries.FindAsync(new BsonDocument())

      public static async Task SeedAsync(IMongoDatabase _database)
      {
      var websiteStates = _database.GetCollection<WEBSITE_STATES>("Website_States");

      // Check and see if we have any website users
      double totalDocuments = websiteStates.CountDocuments(FilterDefinition<WEBSITE\_STATES>.Empty);
      if (totalDocuments == 0)
      {
      
          var websiteCountries = \_database.GetCollection<WEBSITE\_COUNTRIES>("Website\_Countries");
      
          try
          {
              using (IAsyncCursor<WEBSITE\_COUNTRIES> cursor = await websiteCountries.FindAsync(new BsonDocument()))
              {
                  IEnumerable<WEBSITE\_COUNTRIES> batch = cursor.Current; // batch is null here
                  foreach (WEBSITE\_COUNTRIES country in batch)
                  {
                      Console.WriteLine(country.LongName);
                  }
              }
          }
          catch(Exception ex)
          {
              Console.WriteLine(ex.Message.ToString());
          }                
      }            
      

      }

      I wrote this, well sort of copied it, havn't tested it yet. This is in my UserRespository and according to documentation is a CRUD method of getting all the users. What's sort of confusing is the context

      J Offline
      J Offline
      jkirkerx
      wrote on last edited by
      #2

      I have a states collection now in MongoDB I sort of get it now. _ => true must be a wildcard like *, generate a list of countries, as a Result, now I can do the old school loop, which I needed in case I had to walk the code. There was .ForEach(country => { // do work } which did a single execution that may be more efficient. Ended up with this ...

      public static async Task SeedAsync(IMongoDatabase _database)
      {
      var websiteStates = _database.GetCollection<WEBSITE_STATES>("Website_States");

      // Check and see if we have any website users
      double totalDocuments = websiteStates.CountDocuments(FilterDefinition<WEBSITE\_STATES>.Empty);
      if (totalDocuments == 0)
      {
      
          var websiteCountries = \_database.GetCollection<WEBSITE\_COUNTRIES>("Website\_Countries");
          try
          {                    
              foreach (var country in websiteCountries.FindSync(\_ => true).ToListAsync().Result)
              {
                  switch (country.ShortName)
                  {
                      // United States
                      case "US":
      
                          // A
                          ObjectId US\_AL\_Id = ObjectId.GenerateNewId();
                          var state\_AL = new WEBSITE\_STATES() { Id = US\_AL\_Id, DisplayId = US\_AL\_Id.ToString(), CountryId = country.DisplayId,        CountryCode = country.ShortName, LongName = "Alabama", ShortName = "AL", Enabled = true };
                          await websiteStates.InsertOneAsync(state\_AL);
      

      If it ain't broke don't fix it Discover my world at jkirkerx.com

      J 1 Reply Last reply
      0
      • J jkirkerx

        I have a states collection now in MongoDB I sort of get it now. _ => true must be a wildcard like *, generate a list of countries, as a Result, now I can do the old school loop, which I needed in case I had to walk the code. There was .ForEach(country => { // do work } which did a single execution that may be more efficient. Ended up with this ...

        public static async Task SeedAsync(IMongoDatabase _database)
        {
        var websiteStates = _database.GetCollection<WEBSITE_STATES>("Website_States");

        // Check and see if we have any website users
        double totalDocuments = websiteStates.CountDocuments(FilterDefinition<WEBSITE\_STATES>.Empty);
        if (totalDocuments == 0)
        {
        
            var websiteCountries = \_database.GetCollection<WEBSITE\_COUNTRIES>("Website\_Countries");
            try
            {                    
                foreach (var country in websiteCountries.FindSync(\_ => true).ToListAsync().Result)
                {
                    switch (country.ShortName)
                    {
                        // United States
                        case "US":
        
                            // A
                            ObjectId US\_AL\_Id = ObjectId.GenerateNewId();
                            var state\_AL = new WEBSITE\_STATES() { Id = US\_AL\_Id, DisplayId = US\_AL\_Id.ToString(), CountryId = country.DisplayId,        CountryCode = country.ShortName, LongName = "Alabama", ShortName = "AL", Enabled = true };
                            await websiteStates.InsertOneAsync(state\_AL);
        

        If it ain't broke don't fix it Discover my world at jkirkerx.com

        J Offline
        J Offline
        jkirkerx
        wrote on last edited by
        #3

        It was about updating the country collection, and not inserting. Guess there are two ways to work with MongoDB, one being through a context using the driver, and the other working with the MongoDB .Net Core driver straight. This is where I got confused. So I'm using my MongoDBContext in my repositories which are CRUD and just the driver in my services which are REST. Anyways, this is just a learning exercise for later use. I'll dump it and replace it with a text file written in the same BSON format later down the road. But at least I got this working for now, well I haven't consumed yet so I'll find out.

        // Let See if we can inject the States collection into Countries/States
        var filter_US = Builders.Filter.Eq(s => s.ShortName, country.ShortName.ToUpper());
        var update_US = Builders.Update.Set(s => s.States, states_US);
        await websiteCountries.UpdateOneAsync(filter_US, update_US);

        And my result, I saw Arizona is wrong, fixed.

        {
        "_id" : ObjectId("5b8434defb1e6524f8cc0554"),
        "DisplayId" : "5b8434defb1e6524f8cc0554",
        "LongName" : "United States",
        "ShortName" : "US",
        "States" : [
        {
        "_id" : ObjectId("5b8434dffb1e6524f8cc0582"),
        "Name" : "Alabama",
        "Abbr" : "AL"
        },
        {
        "_id" : ObjectId("5b8434dffb1e6524f8cc0583"),
        "Name" : "Alaska",
        "Abbr" : "AK"
        },
        {
        "_id" : ObjectId("5b8434dffb1e6524f8cc0583"),
        "Name" : "Arizona",
        "Abbr" : "AZ"
        },
        {
        "_id" : ObjectId("5b8434dffb1e6524f8cc0585"),
        "Name" : "Arkansas",
        "Abbr" : "AR"
        },

        On a side not about my Angular V6 .Net Core 2.1 training exercise: I finally got all my folders and files organized efficiently. Basically modules, components and services in Angular, plus my routing with lazy loading is correct. Figured out how to change navbars and footers using *ngIf. Got my new Auth Guard authentication working in Angular, including the Auth0 token and wrote a REST service in .Net Core to handle it, with cookies and token generation. My ContactUs works with my CRUD Repository, just have to write the email part, and figure out if I should do it in .Net Core, Angular or write something in NodeJS for it. Perhaps a .Net console app. So now I can move forward with more head scratchers and frustration. What I have learned so far is that Angular V6 is one th

        1 Reply Last reply
        0
        Reply
        • Reply as topic
        Log in to reply
        • Oldest to Newest
        • Newest to Oldest
        • Most Votes


        • Login

        • Don't have an account? Register

        • Login or register to search.
        • First post
          Last post
        0
        • Categories
        • Recent
        • Tags
        • Popular
        • World
        • Users
        • Groups