我正在使用mongoose-plugin-autoinc,一个“一段
时间未维护的mongoose-auto-increment的分支”,为插入到我的集合中的每个文档创建从 0 开始的自动生成索引 _id。
这是我的两个主要文件:
模型.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
});
服务器.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
当我需要订购它们以便正确访问和操作文档时。
有什么帮助吗?