【问题标题】:Add new field to nodeJs model with mongodb使用 mongodb 向 nodeJs 模型添加新字段
【发布时间】:2020-05-08 13:50:00
【问题描述】:

我在 nodeJs api 中有一个用户模型,并使用 mongo db 和 Angular 作为前端框架,我想向我的用户模型添加一个新字段,我所做的是添加名为:“municipalityDateChange”的字段并尝试要从 angular 向 nodeApi 发送 http 请求并记录响应,用户确实包含默认为 null 的新字段!

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
  },
  city: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'City'
  },
  municipalityDateChange: {
    type: Date,
    default: null
  },
  service: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Service'
  },
  postalCode: {
    type: String
  },
  gender: {
    type: String
  },
  age: {
    type: Number
  },
  birthDate: {
    type: Date
  },
  profession: {
    type: String
  },
  tokens: [{
    token: {
      type: String,
      // required: true
    }
  }],
  token: {
    type: String
  },
  type: {
    type: String,
    enum: ['superAdmin', 'president', 'chefService', 'secretaireGeneral', 'conseillerMunicipal', 'citoyen'],
    default: 'citoyen'
  },
  activated: {
    type: Boolean,
    default: false
  },
  suspended: {
    type: Boolean,
    default: false
  },
  avatar: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'File'
  },
  confirmationCode: {
    type: Number
  },
  resetPasswordCode: {
    type: Number
  },
  codeSent: {
    type: Number,
    default: 0
  },
  allInfo: {
    type: Boolean,
    default: false
  },
  propositions: [{
    evaluation: {
      type: String,
      enum: ['like', 'dislike']
    },
    proposition: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Proposition'
    }
  }],
  commissions: [{
    type: String
  }]
}, {
  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)

* 用户控制器*

export async function getOne (req, res) {
  try {
    const user = await User.findById({
      _id: req.params.id
    })
      .populate('avatar')
      // .populate('city')
      // .populate('service')
      .select('firstName lastName type avatar phone email gender age postalCode address profession activated suspended municipalityDateChange')
      .lean()
      .exec()

    user.avatar ? user.avatar = user.avatar.filePath : delete user.avatar

    return res.json(user)
  } catch (error) {
    console.log(error)
    return res.status(500).end()
  }
}

ts

  this.http.get('api/user').subscribe(user => {
      console.log("current user", user)
      this.currentUser = user;
})

日志没有显示用户有新文件!

在这种情况下我应该怎么做?更新我所有的收藏文档或有其他方法在我的模型中设置新文件?

【问题讨论】:

    标签: node.js angular mongodb typescript model


    【解决方案1】:

    我认为您需要将 municipalityDateChange 的默认密钥删除为:

    {
        type: Date
    }
    

    【讨论】:

    • 如果还没有显示,尝试添加 required:true 。
    猜你喜欢
    • 2012-10-27
    • 1970-01-01
    • 2016-09-26
    • 2014-08-10
    • 2020-11-04
    • 1970-01-01
    • 2017-09-27
    • 2021-10-18
    • 1970-01-01
    相关资源
    最近更新 更多