node.js - NodeJs / Mongo:在模型中添加新文件
问题描述
我想在这里问一个关于在我的 nodeJs api 中的现有模型中添加新字段的技术问题,假设我有一个这样的用户模型:
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});
推荐阅读
- java - 如何将 Java 中的 Sha-512 哈希转换为其等效的 Node.js
- node.js - 用斜杠快速化 url 正则表达式
- opencv - 用于创建窗口的 OpenCV highgui 指定合成器后端(X11、Wayland、OpenGL)
- reactjs - JSX 元素 <...> 中的两个变量 {...}
- amcharts - 如何根据 amcharts 4 中的 ajax 数据更改烛台的颜色?
- reinforcement-learning - 一步多动作,强化学习
- git - 无法从 git 提交创建补丁 创建补丁时出错:错误:无法读取对象
- javascript - 将数字转换为字母
- java - JCenter 弃用;对 Gradle 和 Android 的影响
- php - PHP请求没有获得价值