Добавить новое поле в модель nodeJs с помощью mongodb - PullRequest
1 голос
/ 07 мая 2020

У меня есть модель пользователя в nodeJs api, и я работаю с mon go db и Angular в качестве инфраструктуры frontEnd, я хочу добавить новое поле в свою модель пользователя. Я добавил поле с именем : "municipalityDateChange" и попробуйте отправить http-запрос от angular на nodeApi и зарегистрируйте ответ, пользователь действительно содержит новое поле, которое по умолчанию имеет значение 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)

* user контроллер *

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;
})

в журнале не отображается, что пользователь ввел новое поле!

что делать в тонком футляре? обновить всю мою коллекцию до c или есть другой способ установить новое поле в моей модели?

1 Ответ

0 голосов
/ 08 мая 2020

Я думаю, вам нужно удалить ключ по умолчанию для municipalityDateChange на:

{
    type: Date
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...