首页 > 解决方案 > 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 进行迁移。我的数据库中所有已注册的对象呢?如何使用新字段更新这些文档?

标签: node.jsdatabasemongodbmodelmigration

解决方案


您可以随时更改模型以添加新字段。只需编辑您的 model.js 以添加一个新的 isArchived 字段。如果要更新所有现有文档,只需运行

User.update({},{isArchived: <your value here>},{multi: true});

推荐阅读