0

I am using mongoose-plugin-autoinc, a "a fork of mongoose-auto-increment which has not been maintained in a while" to created auto-generated index _id starting from 0 for each document inserted in my collection.
Here are my two main files:

models.js

let informationAssetsrow = new Schema({
  ref: {
    type: String
  },
  dep: {
    type: String
  },
  infAss: {
    type: String
  },
  crJls: {
    type: String
  },
  classification: {
    type: String
  },
  bsOwn: {
    type: String
  },
  dtOwn: {
    type: String
  },
  cmts: {
    type: String
  },

  //THIS IS HOW YOU CAN DEFINE YOUR OWN ID
  /**
   *  truck_id: {
    type: Schema.ObjectId, auto: true
  }
   */

}, { // This is supposed to make mongoose ignore _id but it didn't
  // when I declare _id it actually ignores it -_-
  //_id: false
   autoIndex: false 
})
informationAssetsrow.plugin(autoIncrement, 'informationAssetsRow');
 informationAssetsrow.plugin(autoIncrement, {
  model: 'informationAssetsRow',
  startAt: 0,
  incrementBy: 1
});

server.js

router.route('/fillinformationAssets').post((req, res) => {
        informationAssetsrow.insertMany([req.body[0], req.body[1], req.body[2], req.body[3], req.body[4], req.body[5], req.body[6]], {
            multi: true
        }).then(documentsInserted => {
            console.log('documentsInserted: ', documentsInserted);
        });
    });

The result in the database is:

{
    "_id": 1,
    "ref": "FIRST",
    "dep": "FIRST",
    "infAss": "FIRST",
    "crJls": "FIRST",
    "classification": "FIRST",
    "bsOwn": "FIRST",
    "dtOwn": "FIRST",
    "cmts": "FIRST",
    "__v": 0
}, {
    "_id": 3,
    "dep": "TWO",
    "ref": "TWO",
    "infAss": "TWO",
    "crJls": "TWO",
    "classification": "TWO",
    "bsOwn": "TWO",
    "dtOwn": "TWO",
    "cmts": "TWO",
    "__v": 0
}, {
    "_id": 2,
    "ref": "THREE",
    "dep": "THREE",
    "infAss": "THREE",
    "crJls": "THREE",
    "classification": "THREE",
    "bsOwn": "THREE",
    "dtOwn": "THREE",
    "cmts": "THREE",
    "__v": 0
}

As you see the documents are inserted in order (One,Two,Three).
However, the

_id index

is being incremented sporadically:

First document got _id=1
Second Document got _id=3
Third Document got _id=2

When I need them to be ordered in order to access and manipulate the documents properly.
Any help?

AG_HIHI
  • 1,705
  • 5
  • 27
  • 69
  • Did you tried to put `_id:false` inside your schema and enable `autoIndex`. then try to run just using `truck_id: { type: Schema.Types.ObjectId}`. You are missing `.Types` though in your `truck_id {type}` – Shivam Jul 25 '19 at 16:50
  • I think you misunderstood my problem. My problem is that the _id is getting incremented no in order 1-2-3-4... – AG_HIHI Jul 26 '19 at 08:42
  • @ShivamSood I have found a solution check-out my answer please and let me know what you think – AG_HIHI Jul 26 '19 at 10:09

1 Answers1

0

I still do not know why the _id gets incremented in a disordered manner. But, I did find a solution to make the documents labeled with ordered _ids. This is the data in the front-end that I want to save in the database:
enter image description here
And here are the documents inserted with ordered _id:
enter image description here
Here's how I made my code work as described above:

var async = require('async');

router.route('/fillinformationAssets').post((req, res) => {
    informationAssetsrow.remove({}, (err) => {
        if (err)
            console.log(err);
        else {
            // res.json("informationAssets Collection has been dropped!");
            /*** UPDATE CODE  */
            console.log('REQ.body of informationAssets is ', req.body);
            res.json('Action Plan data has been received on the server side')
            //A Mongoose model doesn't have an insertOne method. Use the create method instead:
            /*** UPDATE CODE  */
            async.series([
                function (callback) {
            informationAssetsrow.create(req.body[0])
                  .then(() => callback(null, 'Row 1 Inserted'));
                },
                function (callback) {
            informationAssetsrow.create(req.body[1])
                  .then(() => callback(null, 'Row 2 Inserted'));
            
                },
                function (callback) {
            informationAssetsrow.create(req.body[2])
                  .then(() => callback(null, 'Row 3 Inserted'));
                },
                function (callback) {
            informationAssetsrow.create(req.body[3])
                  .then(() => callback(null, 'Row 3 Inserted'));
                },
                function (callback) {
            informationAssetsrow.create(req.body[4])
                  .then(() => callback(null, 'Row 5 Inserted'));
                },
              ], function (error, results) {
                console.log(results);
              });
        }
    });
})

Using Async allows me to write synchronous requests. I.e: I get to decide the order of execution of requests.
Hope this helps someone.

Community
  • 1
  • 1
AG_HIHI
  • 1,705
  • 5
  • 27
  • 69
  • So u are planning to repeat callbacks manually when u have let’s say 1000 rows? Nodejs is async that means you shouldn’t be making synchronized calls unless direly needed. Just think how will you scale ur app when u have multiple users, accessing and trying to add at same time – Shivam Jul 26 '19 at 14:49
  • @ShivamSood I know this is not scalable. I don't need to scale for this particular use case. Sadly this is the only solution I found. And I used it as a last resort. – AG_HIHI Jul 26 '19 at 16:35