Tuesday, April 3, 2018

How to add a custom field in mongoose object?

mongoose is an object data modeling (ODM) powerful modeling library to handle your data.

it provides a schema-based model in your application. It includes built-in typecasting, validation, query building, business logic, etc.

By using mongoose we can make our own model schema and we can prevent to store and set another field which is not in the predefined model.

Here, we will discuss regarding how to set custom field or add a new field which is not defined in our model.

By default, schema has "strict: true" option for security. if we need to store \ set some extra field which is not in model's property, by using this option it is possible.

EX 1: using strict in schema 

user.js 
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var userSchema = new Schema({
    user_name: {
        type: String
    },
    first_name: {
        type: String
    },
    last_name: {
        type: String
    },
    gender: {
        type: String,
        enum: ['Male', 'Female']
    },
    email: {
        type: String
    },
    password: {
        type: String
    },
    is_active: {
        type: Number
    }
}, {
    strict: false,
    collection: 'user'
});

var User = module.exports = mongoose.model("User", userSchema);

api.js
var express = require('express');
var router = express.Router();
var User = require('../models/userProfile');

router
    .route('/api/cuisine/getcuisineListWithCounter')
    .get(function(req, res) {
            User.find({}, function(err, user) {
                if (err) {
                    res.json({ status: 0 , message: err });
                } else {
                    if(!!user && user.length> 0){
                        user.map(function(userObj){
                            if(userObj.gender ==="Male"){
                                obj.set('defaultImage', "Male user's default image path");
                            }else if(userObj.gender ==="Female"){
                                obj.set('defaultImage', "Female user's default image path");
                            }
                        });
                        console.log("updated user's information");
                        console.log(user);
                        res.json({ status: 0 , data: user });
                    }
                }
            });
    });

in above demo 1, we have set schema level strict false. so we can add new filed like as "defaultImage" in mongoose object.

if we will not use strict: false then we can not set this type of any extra field.

EX 2: use strict when required in mongoose object

user.js 
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var userSchema = new Schema({
    user_name: {
        type: String
    },
    first_name: {
        type: String
    },
    last_name: {
        type: String
    },
    gender: {
        type: String,
        enum: ['Male', 'Female']
    },
    email: {
        type: String
    },
    password: {
        type: String
    },
    is_active: {
        type: Number
    }
},{
    collection: 'user'
});

var User = module.exports = mongoose.model("User", userSchema);

api.js
var express = require('express');
var router = express.Router();
var User = require('../models/userProfile');

router
    .route('/api/cuisine/getcuisineListWithCounter')
    .get(function(req, res) {
            User.find({}, function(err, user) {
                if (err) {
                    res.json({ status: 0 , message: err });
                } else {
                    if(!!user && user.length> 0){
                        user.map(function(userObj){
                            if(userObj.gender ==="Male"){
                                obj.set('defaultImage', "Male user's default image path", {strict: false});
                            }else if(userObj.gender ==="Female"){
                                obj.set('defaultImage', "Female user's default image path", {strict: false});
                            }
                        });
                        console.log("updated user's information");
                        console.log(user);
                        res.json({ status: 0 , data: user });
                    }
                }
            });
    });

in above demo 2, we have not set schema level strict false means it will take by default strict true. so we have to add new filed by using extra options in set method.

2 comments: