Wednesday, 12 April 2017

The writing sequence of Schema Creation in Mongoose

I am creating Schema and instance method for the Schema in Mongoose. However, I faced some problems.

This is the part of code in models

const AnswerSchema = new Schema({
  text: String,
  createdAt: {type: Date, default: Date.now},
  updatedAt: {type: Date, default: Date.now},
  votes: {type: Number, default: 0}
})


AnswerSchema.method('update', function (updates, callback) {
  Object.assign(this, updates, {updatedAt: new Date()})
  this.parent().save(callback)
})

AnswerSchema.method('vote', function (vote, callback) {
  if (vote === 'up') {
    this.votes += 1
  } else {
    this.votes -= 1
  }
  this.parent().save(callback)
})

const QuestionSchema = new Schema({
  text: String,
  createdAt: {type: Date, default: Date.now},
  answers: [AnswerSchema]         
})

and it will show me that The #update method is not available on EmbeddedDocuments when I get the PUT request in my routes.

router.put('/:qID/answers/:aID', (req, res, next) => {
  req.answer.update(req.body, function (err, result) {    // update 這個是寫在 Model 的 instance method
    if (err) return next(err)
    res.json(result)
  })
})

However, if I changed the sequence of my code, it works fine:

const AnswerSchema = new Schema({
  text: String,
  createdAt: {type: Date, default: Date.now},
  updatedAt: {type: Date, default: Date.now},
  votes: {type: Number, default: 0}
})

AnswerSchema.method('update', function (updates, callback) {
  Object.assign(this, updates, {updatedAt: new Date()})
  this.parent().save(callback)
})

AnswerSchema.method('vote', function (vote, callback) {
  if (vote === 'up') {
    this.votes += 1
  } else {
    this.votes -= 1
  }
  this.parent().save(callback)
})

const QuestionSchema = new Schema({
  text: String,
  createdAt: {type: Date, default: Date.now},
  answers: [AnswerSchema]           
})

I know my AnswerSchema is nested in QuestionSchema, but why the sequence results in the problem. Could someone explain why this happens for me??



via PJCHENder

No comments:

Post a Comment