我想在这里问一个关于在我的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的字段,最好的方法是什么?是可能的工作与迁移与noSql的DB.和什么所有注册的对象在我的数据库;如何更新这些文件与新的字段?
你可以在任何时候改变模型来添加一个新的字段。只需编辑你的model.js来添加一个新的isArchived字段。如果你想更新所有现有的文档,只需执行
User.update({},{isArchived: <your value here>},{multi: true});