【问题标题】:Using mongoose-autoincrement with insertMany request populates the _id index in a disordered manner将 mongoose-autoincrement 与 insertMany 请求一起使用会以无序的方式填充 _id 索引
【发布时间】:2019-12-03 21:55:22
【问题描述】:

我正在使用mongoose-plugin-autoinc,一个“mongoose-auto-increment 的分支” 有一段时间没有维护”为插入到我的集合中的每个文档创建从 0 开始的自动生成的索引 _id。
这是我的两个主要文件:

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);
        });
    });

数据库中的结果是:

{
    "_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
}

如您所见,文档是按顺序插入的(一、二、三)。
然而,

_id 索引

偶尔增加:

第一个文档得到 _id=1
第二个文档得到 _id=3
第三份文件 得到_id=2

当我需要订购它们以便正确访问和操作文档时。
有什么帮助吗?

【问题讨论】:

  • 您是否尝试将_id:false 放入您的架构中并启用autoIndex。然后尝试仅使用truck_id: { type: Schema.Types.ObjectId} 运行。尽管在您的 truck_id {type} 中,但您缺少 .Types
  • 我想你误解了我的问题。我的问题是 _id 没有按 1-2-3-4 的顺序递增...
  • @ShivamSood 我找到了解决方案,请查看我的答案并告诉我您的想法

标签: node.js mongodb mongoose mongoose-auto-increment


【解决方案1】:

我仍然不知道为什么 _id 会以无序的方式递增。但是,我确实找到了一个解决方案来制作带有有序 _ids 标记的文档。 这是我要保存在数据库中的前端数据:

以下是使用有序 _id 插入的文档:

以下是我如何使我的代码按上述方式工作:

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);
              });
        }
    });
})

使用异步允许我编写同步请求。即:我可以决定请求的执行顺序。
希望这对某人有所帮助。

【讨论】:

  • 所以你打算在假设有 1000 行时手动重复回调? Nodejs 是异步的,这意味着除非迫切需要,否则您不应该进行同步调用。试想一下,当您有多个用户,同时访问和尝试添加时,您将如何扩展您的应用程序
  • @ShivamSood 我知道这是不可扩展的。我不需要针对这个特定的用例进行扩展。可悲的是,这是我找到的唯一解决方案。我把它作为最后的手段。
猜你喜欢
  • 2021-01-02
  • 1970-01-01
  • 2020-07-20
  • 2017-10-06
  • 2021-12-20
  • 2017-09-17
  • 2023-04-08
  • 2018-03-07
  • 2023-03-08
相关资源
最近更新 更多