Increment a Value on a MongoDB field, using a Schema Method

PHOTO EMBED

Sat May 22 2021 03:47:11 GMT+0000 (Coordinated Universal Time)

Saved by @junior #javascript

const LyricSchema = new Schema({
  song: {
    type: Schema.Types.ObjectId,
    ref: 'song'
  },
  likes: { type: Number, default: 0 },
  content: { type: String }
});

LyricSchema.statics.like = function(id) {
  const Lyric = mongoose.model('lyric');

  return Lyric.findById(id)
    .then(lyric => {
      ++lyric.likes;
      return lyric.save();
    })
}

mongoose.model('lyric', LyricSchema);
content_copyCOPY

here we increment the likes fields, using a static method on schema called "like"