Advertisement
Ludwiq

Node.JS Note Model

Feb 14th, 2016
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2.  
  3. var mongoose = require('mongoose'),
  4.     Schema = mongoose.Schema,
  5.     Tag = require('./tag.model'); //another mongoose Model
  6.  
  7. var NoteSchema = new Schema({
  8.     name: String,
  9.     info: String,
  10.     active: Boolean,
  11.     tags: [{ type: String, ref: 'Tag' }],
  12. });
  13.  
  14. NoteSchema.virtual('tagsAsString').get(function () {
  15.     var result = "";
  16.     for (var x in this.tags) {
  17.         result += this.tags[x].name + " ";
  18.     }
  19.     return result;
  20. });
  21.  
  22. NoteSchema.virtual('tagsAsString').set(function (data) {
  23.     var split = data.split(' ');
  24.     this.tags = new Array();
  25.     for (var s in split) {
  26.         Tag.find({ name: split[s] }).exec(function (err, tag) {
  27.             if (tag == undefined || tag == 0 || tag.length == 0) {
  28.                 tag = new Tag({ name: split[s] });
  29.                 tag.save(function (err) {
  30.                     if (err) console.error(err);
  31.                 });
  32.                 this.tags.push(tag.name);
  33.             }
  34.             else {
  35.                 this.tags.push(tag.name);
  36.             }
  37.  
  38.             this.save(function (err) {
  39.                 if (err) console.error(err);
  40.             });
  41.         });
  42.     }
  43. });
  44.  
  45. module.exports = mongoose.model('Note', NoteSchema);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement