Я хочу задать технический вопрос о добавлении нового поля в существующую модель в моем nodeJs api, предполагая, что у меня есть такая модель User:
import mongoose, {
Schema
} from 'mongoose'
import mongooseDelete from 'mongoose-delete'
import bcrypt from 'bcrypt'
import crypto from 'crypto'
const userSchema = new Schema({
firstName: {
type: String
},
lastName: {
type: String
},
phone: {
type: Number
},
email: {
type: String
},
hashedPassword: {
type: String
},
address: {
type: String
},
profession: {
type: String
},
tokens: [{
token: {
type: String,
// required: true
}
}],
token: {
type: String
},
activated: {
type: Boolean,
default: false
},
avatar: {
type: mongoose.Schema.Types.ObjectId,
ref: 'File'
},
{
timestamps: true
})
userSchema.virtual('password').set(function (password) {
this.hashedPassword = bcrypt.hashSync(password, bcrypt.genSaltSync(10))
})
function calculateAge(birthDate, otherDate) {
birthDate = new Date(birthDate);
otherDate = new Date(otherDate);
var years = (otherDate.getFullYear() - birthDate.getFullYear())
if (otherDate.getMonth() < birthDate.getMonth() ||
otherDate.getMonth() == birthDate.getMonth() && otherDate.getDate() < birthDate.getDate()) {
years--;
}
return years
}
userSchema.pre('save', function (next) {
this.age = calculateAge(this.birthDate, new Date())
next()
})
userSchema.methods = {
comparePassword(candidatePassword) {
return bcrypt.compareSync(candidatePassword, this.hashedPassword)
}
}
userSchema.methods.generateAuthToken = async function () {
// Generate an auth token for the user
const user = this
const token = crypto
.createHash('sha256')
.update(crypto.randomBytes(48).toString('hex'))
.digest('hex')
user.tokens = user.tokens.concat({
token
})
await user.save()
return token
}
userSchema.plugin(mongooseDelete, {
overrideMethods: 'all',
deletedAt: true,
deletedBy: true
})
export default mongoose.model('User', userSchema)
Я хочу добавить поле с именем isArchived, как лучше всего это сделать? Возможна работа с миграцией без Sql БД. а как насчет всех зарегистрированных объектов в моей базе данных; как обновить эти документы новым полем?