我有一個貓鼬模式,如下所示
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const personSchema = new Schema({
name: {type: String},
age: {type: Number},
internalId: {type: Number},
})
personSchema.pre('save', function (next) {
if (this.isNew) {this.id = this._id;}
next()
})
const Person = mongoose.model("Person", personSchema);
exports.Person = Person
我希望內部 ID 欄位是累積的內部 ID。這意味著第一個人的 internalId 為 1,第二個人的 internalId 為 2,依此類推。
我該如何繼續這樣做。我需要添加一個全域值還是創建一個函式?
uj5u.com熱心網友回復:
您可以使用npm package
稱為mongoose-sequence
.
它允許您定義要自動遞增的欄位,并且每次創建該模型的新物件時都會生成該欄位。如果您使用該軟體包,您的代碼將如下所示:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const AutoIncrement = require('mongoose-sequence')(mongoose);
const personSchema = new Schema({
name: {type: String},
age: {type: Number},
});
personSchema.plugin(AutoIncrement, {inc_field: 'internalId'});
const Person = mongoose.model("Person", personSchema);
exports.Person = Person;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/506432.html
標籤:javascript 节点.js mongodb 猫鼬 猫鼬模式