mongoose require code example

Example 1: mongoose validate example

// example AUTH SCHEMA

const mongoose = require('mongoose')
const bcryptjs = require('bcryptjs')
const findOrCreate = require('mongoose-findorcreate')
const validator = require('mongoose-validator')
const Schema = mongoose.Schema

const setAuthSchema = new Schema(
  {
    username: {
      type: String,
      trim: true,
      required: true
    },
    email: {
      type: String,
      lowercase: true,
      trim: true,
      validate: [
        validator({
          validator: 'isEmail',
          message: 'Oops..please enter valid email'
        })
      ],
      required: true
    },
    password: {
      type: String,
      minlength: 8,
      maxlength: 16,
      trim: true,
      required: true
    },
    authsc: {
      idsocial: {
        type: String,
        trim: true,
        default: null
      },
      username: {
        type: String,
        trim: true,
        default: null
      },
      fullname: {
        type: String,
        trim: true,
        default: null
      },
      email: {
        type: String,
        lowercase: true,
        trim: true,
        validate: [
          validator({
            validator: 'isEmail',
            message: 'Oops..please enter valid email'
          })
        ],
        default: null
      },
      gender: {
        type: String,
        trim: true,
        default: null
      },
      avatar: {
        type: String,
        trim: true,
        default: null
      },
      provider: {
        type: String,
        trim: true,
        default: null
      }
    },
    role: {
      type: String,
      trim: true,
      default: 'user'
    },
    isActive: {
      type: Boolean,
      trim: true,
      default: false
    }
  },
  { timestamps: true }
)

setAuthSchema.plugin(findOrCreate)

setAuthSchema.pre('save', function (next) {
  if (this.isModified('password')) {
    const salt = bcryptjs.genSaltSync(10)
    this.password = bcryptjs.hashSync(this.password, salt)
    return next()
  }
})

setAuthSchema.static('hashPassword', (password) => {
  if (password) {
    const salt = bcryptjs.genSaltSync(10)
    return bcryptjs.hashSync(password, salt)
  }
})

setAuthSchema.static('verifyPassword', (password, hash) => {
  if (password && hash) {
    return bcryptjs.compareSync(password, hash)
  }
})

const AuthSchema = mongoose.model('auth', setAuthSchema)
module.exports = { AuthSchema }

Example 2: Mongoose node js

// getting-started.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // we're connected!
});

Example 3: mongoose

import express from 'express';
or
const exporess = require('express');
import mongoose from 'mongoose';
or
const mongoose = require('mongoose');
const app = express();
mongoose.connect('mongodb://localhost:27017/mongo-tree' , {
    useNewUrlParser: true,
    useUnifiedTopology: true
});

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('connected db')
});
app.use('/', (req, res) => {
    res.send('hello');
}
);
const port = process.env.PORT || 5000
app.listen(port, () => {
console.log('running');
})
//for es6 >npm i @babel/core @babel/node @babel/preset-env --save-dev

//create  .babelrc file and put this 
{
    "presets": [
        "@babel/preset-env"
    ]
}
//and package.json
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon --exec babel-node server"
  },

Example 4: node js + mongoose

await mongoose.connect('mongodb://localhost/my_database', {  useNewUrlParser: true,  useUnifiedTopology: true});

Example 5: node js + mongoose

const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // we're connected!
});

Example 6: mongoose

mongoose initial setup