<commit_before>---
layout: post
title: NodeJS Mongoose
category: NodeJS
tags: [nodejs]
---

This is quick note after learning Mongoose.

## Default value in schema

We could define default values on schema.

1. **Default values** directly.
2. **Default function** - set the default schema option to a function and use the return value as the default.

{% highlight nodejs %}
var mongoose = require('mongoose');

mongoose.connect("mongodb://localhost/mongodemo");

var UserSchema = new mongoose.Schema({
    nickname: {
        type: String,
        default: 'dchuan' // Default value
    },
    regTime: {
        type: Date,
        default: Date.now // Default function
    }
});

var User = mongoose.model('User', UserSchema);

var user = new User(); // Without setting anything. So with default values

console.log('user: ', user);

// output
// user:  { nickname: 'dchuan',
//    regTime: Sat Apr 02 2016 17:14:57 GMT+0200 (Romance Daylight Time),
//    _id: 56ffe1f11c6628a4037ea514 }
{% endhighlight %}

## Getters and Setters

Getters and setters could change attributes defined by the keys and values in the document.

* Setter: **transform data before it is stored mongodb**.
* Getter: **transform the representation of the data when retreive from mongodb**.

{% highlight nodejs %}
var mongoose = require('mongoose');

mongoose.connect("mongodb://localhost/mongodemo");

var UserSchema = new mongoose.Schema({
    nickname: {
        type: String,
        trim: true  // Delete spaces at the begining and in the end
    },
    blogurl: {
        type: String,
        // Setter. So all the url without http/https will be added prefix http before storing in mongoDB
        set: function(url) {

            if(!url) return url;

            if(0 !== url.indexOf('http://') && 0 !== url.indexOf('https://'))
                url = 'http://' + url;

            return url;
        }
    }
});

var User = mongoose.model('User', UserSchema);

var user = new User({
    blogurl: "dongchuan.github.io"
});

console.log('user: ', user);
// output
// user:  { _id: 570038ade8cb4c9023875290,
//    blogurl: 'http://dongchuan.github.io',
//    nickname: 'dchuan' }
{% endhighlight %}

Another example about getter:

{% highlight nodejs %}
var UserSchema = new mongoose.Schema({
  blogurl: {
    type: String,
    // Getter. After retreiving data, prefix http:// will be added if not exist
    get: function(url){

      if(!url) return url;

      if(0 !== url.indexOf('http://') && 0 !== url.indexOf("https://"))
        url = 'http://' + url;

      return url;
    }
  }
});

var User = mongoose.model('User', UserSchema);

var user = new User({
  blogurl: 'dongchuan.github.io'
});

user.save(function(err){
  if(err) {
    return console.log('save error:' , err);
  }

  // 'get' will be invoked here to add "http://"
  console.log('blog url: ', user.blogurl);
});
{% endhighlight %}

## Validation

Like in html, available validations are:

for type: Number

* required: true/false
* max: Number
* min: Number

for type: String

* required: true/false
* enum: [A, B, C]
* match: regexp
* maxlength 
* minlength

We could also customize a validation:

* validate: function(){} - customized validation. Must return true/false

{% highlight nodejs %}
var mongoose = require('mongoose');<commit_msg>update highlight<commit_after>---
layout: post
title: NodeJS Mongoose
category: NodeJS
tags: [nodejs]
---

This is quick note after learning Mongoose.

## Default value in schema

We could define default values on schema.

1. **Default values** directly.
2. **Default function** - set the default schema option to a function and use the return value as the default.

{% highlight javascript %}
var mongoose = require('mongoose');

mongoose.connect("mongodb://localhost/mongodemo");

var UserSchema = new mongoose.Schema({
    nickname: {
        type: String,
        default: 'dchuan' // Default value
    },
    regTime: {
        type: Date,
        default: Date.now // Default function
    }
});

var User = mongoose.model('User', UserSchema);

var user = new User(); // Without setting anything. So with default values

console.log('user: ', user);

// output
// user:  { nickname: 'dchuan',
//    regTime: Sat Apr 02 2016 17:14:57 GMT+0200 (Romance Daylight Time),
//    _id: 56ffe1f11c6628a4037ea514 }
{% endhighlight %}

## Getters and Setters

Getters and setters could change attributes defined by the keys and values in the document.

* Setter: **transform data before it is stored mongodb**.
* Getter: **transform the representation of the data when retreive from mongodb**.

{% highlight javascript %}
var mongoose = require('mongoose');

mongoose.connect("mongodb://localhost/mongodemo");

var UserSchema = new mongoose.Schema({
    nickname: {
        type: String,
        trim: true  // Delete spaces at the begining and in the end
    },
    blogurl: {
        type: String,
        // Setter. So all the url without http/https will be added prefix http before storing in mongoDB
        set: function(url) {

            if(!url) return url;

            if(0 !== url.indexOf('http://') && 0 !== url.indexOf('https://'))
                url = 'http://' + url;

            return url;
        }
    }
});

var User = mongoose.model('User', UserSchema);

var user = new User({
    blogurl: "dongchuan.github.io"
});

console.log('user: ', user);
// output
// user:  { _id: 570038ade8cb4c9023875290,
//    blogurl: 'http://dongchuan.github.io',
//    nickname: 'dchuan' }
{% endhighlight %}

Another example about getter:

{% highlight javascript %}
var UserSchema = new mongoose.Schema({
  blogurl: {
    type: String,
    // Getter. After retreiving data, prefix http:// will be added if not exist
    get: function(url){

      if(!url) return url;

      if(0 !== url.indexOf('http://') && 0 !== url.indexOf("https://"))
        url = 'http://' + url;

      return url;
    }
  }
});

var User = mongoose.model('User', UserSchema);

var user = new User({
  blogurl: 'dongchuan.github.io'
});

user.save(function(err){
  if(err) {
    return console.log('save error:' , err);
  }

  // 'get' will be invoked here to add "http://"
  console.log('blog url: ', user.blogurl);
});
{% endhighlight %}

## Validation

Like in html, available validations are:

**for type: Number**

* required: true/false
* max: Number
* min: Number

**for type: String**

* required: true/false
* enum: [A, B, C]
* match: regexp
* maxlength: Number
* minlength: Number

We could also **customize a validation**:

* `validate: function(){}` - customized validation. Must return true/false

{% highlight javascript %}
var mongoose = require('mongoose');
{'fraction_non_alphanumeric': 0.1424706943192065, 'fraction_numerical': 0.016831980763450556, 'mean_word_length': 3.035779260157671, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3294037', 'n_tokens_mistral': 2194, 'n_tokens_neox': 2060, 'n_words': 678}