<file_sep>const express = require ('express');
const router = express.Router ();
const Director = require ('../model/Director')
const mongoose = require ('mongoose')


// todo qidirsih ====
router.get('/', (req,res,next) =>{
    const user = Director.find({});

    user.then(data =>{
        res.json(data)
    }).catch(err =>{
        console.log(err)
    })
})

//todo get user ulimiz agregat ==

router.get ('/', (req, res, next) => {
    //usersga kirasan
    const user = Director.aggregate ([
        {
            $lookup: {
                from: 'movies',//users mongo atlasdegi
                localField: '_id',// userni idi bilan movies ni user_id bn bir hil boldi
                foreignField: `user_id`,//Movies ni user_idsini ol uni kino kategoriyaga sol
                as: 'kino',//uni kino qilib oladi
            }
        },
        {

            $unwind: {
                path: `$kino`
                //kino yozilgan joyga kiradi faqat shu tarafini korsatadi
            }
        },
        {
            //todo userni olib uni shu toigfalarini cqaradi
            $group: {
                _id: {
                    _id: `$_id`,
                    name: `$name`,
                    surname: `$surname`,
                    bio: `$bio`,
                },


                //todo || va usersni ichiga moviesni idisiga togri kelgan kino cconnectioni  push qiladi
                movies: {
                    $push: `$kino`
                }


            }


        },
        //qisqartma tutish
        {
            $project: {
                _id: '$_id._id',
                name: '$_id.name',
                surname: '$_id.surname',
                bio: '$_id.bio',
                kino: '$kino'
            }
        }


    ])
    user.then (data => {
        res.json (data)
    }).catch (err => {
        console.log (err)
    })
})


//todo idi orqali tutish

router.get ('/:us_id', (req, res, next) => {
    //usersga kirasan
    const user = Director.aggregate ([

        {
            $match: {
                '_id': mongoose.Types.ObjectId (req.params.us_id)
            }
        },
        {
            $lookup: {
                from: 'movies',//users mongo atlasdegi
                localField: '_id',// userni idi bilan movies ni user_id bn bir hil boldi
                foreignField: `user_id`,//Movies ni user_idsini ol uni kino kategoriyaga sol
                as: 'kino',//uni kino qilib oladi
            }
        },
        {

            $unwind: {
                path: `$kino`
                //kino yozilgan joyga kiradi faqat shu tarafini korsatadi
            }
        },
        {
            //todo userni olib uni shu toigfalarini cqaradi
            $group: {
                _id: {
                    _id: `$_id`,
                    name: `$name`,
                    surname: `$surname`,
                    bio: `$bio`,
                },


                //todo || va usersni ichiga moviesni idisiga togri kelgan kino cconnectioni  push qiladi
                movies: {
                    $push: `$kino`
                }


            }


        },
        //qisqartma tutish
        {
            $project: {
                _id: '$_id._id',
                name: '$_id.name',
                surname: '$_id.surname',
                bio: '$_id.bio',
                kino: '$kino'
            }
        }


    ])
    user.then (data => {
        res.json (data)
    }).catch (err => {
        console.log (err)
    })
})

//todo|| malumot qoshish
router.post ('/', (req, res, next) => {
    const user = new Director (req.body)

    const promise = user.save ();

    promise.then (data => {
        res.json (data)
    }).catch (err => {
        console.log (err)
    })
})

//todo || idi orqali yangilash
router.put ('/:us_id', (req, res) => {
    const promise = Director.findByIdAndUpdate (req.params.us_id, req.body, {new: true});

    promise.then(data =>{
        res.json(data)
    }).catch(err =>{
        console.log(err)
    })
})

//TODO || idi orqali  ochirish - DELETE
router.delete ('/:us_id', (req, res) => {
    const promise = Director.findByIdAndDelete (req.params.us_id);

    promise.then(data =>{
        res.json(data)
    }).catch(err =>{
        console.log(err)
    })
})

//todo || top10 qidirish
router.get ('/:user_id/top10', (req, res, next) => {


    //usersga kirasan
    const user = Director.aggregate ([

        {
            //idisi shunga tori kelsa
            $match: {
                '_id': mongoose.Types.ObjectId (req.params.user_id)
            }
        },
        {
            $lookup: {
                from: 'movies',//users mongo atlasdegi
                localField: '_id',// userni idi bilan movies ni user_id bn bir hil boldi
                foreignField: `user_id`,//Movies ni user_idsini ol uni kino kategoriyaga sol
                as: 'kino',//uni kino qilib oladi
            }
        },
        {

            $unwind: {
                path: `$kino`
                //kino yozilgan joyga kiradi faqat shu tarafini korsatadi
            }
        },
        {
            //todo userni olib uni shu toigfalarini cqaradi
            $group: {
                _id: {
                    _id: `$_id`,
                    name: `$name`,
                    surname: `$surname`,
                    bio: `$bio`,
                },


                //todo || va usersni ichiga moviesni idisiga togri kelgan kino cconnectioni  push qiladi
                movies: {
                    $push: `$kino`
                }


            }


        },
        //qisqartma tutish
        {
            $project: {
                _id: false,
                kino: '$kino'
            }
        }


    ])
    user.then (data => {
        res.json (data)
    }).catch (err => {
        console.log (err)
    })
})

module.exports = router
<file_sep>const express = require ('express');
const router = express.Router ();
const Movies = require ('../model/Movies')

/* GET home page. */
// router.get ('/', (req, res, next) => {
//     res.render ('index', {title: 'Express'});
// });


//todo || --- malumotlar yaratish ---

router.post ('/', (req, res, next) => {

    const movie = new Movies (req.body)

    const promise = movie.save ();

    promise.then (data => {
        res.json (data)
    }).catch (err => {
        console.log (err)
    })

});

//todo Get -- malumotlarni olish

router.get ('/', (req, res, next) => {
    const promise = Movies.find ({})

    promise.then (data => {
        res.json (data)
    }).catch (err => {
        console.log (err)
    })
});

//todo  /api/movies/:id idi orqali tutish
//owatga yozgan idini cqaradi :id
router.get ('/:id', (req, res) => {
    const promise = Movies.findById (req.params.id)

    promise.then (data => {
        res.json (data)
    }).catch (err => {
        console.log (err)
    })

})

//todo || Put - yangilash ---

router.put ('/:id', (req, res) => {
    const promise = Movies.findByIdAndUpdate (
        req.params.id,
        req.body);

    promise.then (data => {
        res.json (data)
    }).catch (err => console.log (err)
    )
})


//todo || udalit qilish ===

router.delete ('/:id', (req, res) => {
    const promise = Movies.findByIdAndRemove (req.params.id);

    promise.then (data => {
        res.json (data)
    }).catch (err => console.log (err)
    )
})

//todo top 10 lani qidiring

router.get ('/top/top10', (req, res, next) => {
    const promise = Movies.find ({}).limit (10).sort ({ovoz_ber: -1})

    promise.then (data => {
        res.json (data)
    }).catch (err => {
        console.log (err)
    })
})


//todo || shu yildan shu  yilgacham bogan <NAME>

router.get ('/yil/:start/:end', (res, req, next) => {

    const {start, end} = req.params
    //todo hama  yilani olamiz
    const promise = Movies.find ({
        year: {'$gte': parseInt (start), '$lte': parseInt (end)}
    })
    promise.then (data => {
        res.json (data)
    }).catch (err => {
        console.log (err)
    })
})


module.exports = router;
<file_sep>const express = require ('express');
const router = express.Router();
const User = require ('../model/Users')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')

/* GET home page. */
router.get ('/', (req, res, next) => {
    res.render ('index', {title: 'Express'});

})

router.post ('/register', (req, res) => {

    //todo || posmanda yozgan kod tuWadi passwordga
    const {username, password} = req.body;

    //todo | passwordegi  123 hashga tushadi 10 talik uzunligi boladi
    bcrypt.hash(password,10,(err,hash)=>{

        const user = new User ({
            username,
            password:hash, //todo || passwordga hashlangan kodi yozadi
        })

        const promise = user.save ();
        promise.then (data => res.json (data))
            .catch (err => console.log (err))

    })


})


//todo ============ auth ===================================
router.post ('/auth', (req, res) => {


    const {username, password} = req.body;

    //username ni user oz ichiga oladi
    User.findOne({ username },(err,user)=>{

        if (err)
            throw err;
        // todo : agar kevotgan user user bolmasa shuni chiqaradi
        if (!user){
            res.json({status:'Topilmadi idi ',msg:"Kirish Muffoqiyatsiz faqat admin kirish mumkun"})
        }
        //todo ||  else da agar user kirsa
        else{
            // parolni  bizaga qaytarib beradi  usernemi passwortini uni soliwtradi
            bcrypt.compare(password,user.password).then((result) =>{
                // agar kegan parol natori  tersa
                if(!result) {
                    res.json ({status: false, msg: "Foydalanuvchi paroli natori "})

                }
                //agar parol tori kelsa  username chiqar
                else{
                    const  payload = {username}
                    // secret_key ni app.js dan olib keladi app.set dagi
                    const token= jwt.sign(payload,req.app.get('secret_key'),{
                        expiresIn:720 //12soat  turadi kompyuterga hotira jonatadi
                    })
                    // res.jsonda uni tutvolamiz korsatgin
                    res.json({
                        status:true,
                        token // 12soatli tokeni koramiz
                    })

                }
            })

        }


    })


})


module.exports = router;
<file_sep>const mongoose = require('mongoose');


const Schema = mongoose.Schema;

const UserSchema = new Schema({
  name:{type:String,required:true},
    surname:String,
    bio:String,
    createdAt:{
      type:Date,
        default:Date.now
    }
})


module.exports = mongoose.model('user',UserSchema)
<file_sep># movieApi
movies
<file_sep>const jwt =require('jsonwebtoken')


//agar token kirtsek yoki postmandan
module.exports =(req,res,next) =>{
    //agar token true bolsa shulardan oladi || yoki url adressdan req.query.token
    const token = req.headers['x-acces-token'] || req.body.token || req.query.token


    //agar token true  bolsa tokeni  raqamlarini tekshiradi
    if(token){
        // tepadegi tokenimiz bolsa  toke ni tekwiradi || err -dec qaytaradi
        jwt.verify(token, req.app.get('secret_key'),(err,dec) =>{
            //agar hato bolsa
            if(err){
                res.json({status:false,msg:'Kira olmaysiz'})
            }
            else{
                req.decoded = dec
                next() //agar togri kelsa next ishlidi otqzvoradi app.jsga
            }
        })
    }
    //registratsiya dan otilmasa shuni qaytaradi
    else{
        res.json({status:false, msg:'token topilmadi '})

    }
}
<file_sep>const chai = require ('chai');
const chaiHttp = require ('chai-http');

const should = chai.should ();
const server = require ('../../app') // app.jsdan userni get gacham oladi

chai.use (chaiHttp)


describe (`bosh sahifani testdan otqizdik`, () => {
    it ('Get method orqali bosh sahifani tekishiruvdan otqazdik', (done) => {
        chai.request (server)
            .get ('/')
            .end ((err, res) => {
                res.should.have.status (200)
                done ()
            })
    })
})
<file_sep>const mongoose = require('mongoose');

module.exports =() =>{
    mongoose.connect('mongodb+srv://madaminov:iphone11@@cluster0.pnhzl.mongodb.net/test',
        {useFindAndModify:true,useUnifiedTopology:true,useNewUrlParser:true,useCreateIndex:true})
    const db = mongoose.connection;
    db.on('open',() =>{
        console.log('Mongo db ishga tushdi')
    })
    db.on('error',(err)=>{
        console.log('Mongoda qayerdadur  hatolik bor',err)
    })
}
<file_sep>const mongoose = require('mongoose')



const Schema = mongoose.Schema;

const MoviesSchema = new Schema({
    title: {
        type:String,
        required:true
    },
    category:String,
    country:String,
    year:Number,
    user_id:Schema.Types.ObjectId,
    ovoz_ber:Number,
    createAt:{
        type:Date,
        default:Date.now,
    }


})

module.exports = mongoose.model('movie',MoviesSchema)
