trying to assign value to schema in schema in mongoose in nodejs

so my mongoose model looks like this

 userName:{
        type:String,
        required:true
    },
    userEmail:{
        type:String,
        required:true
    },
    userGym: gySchema,
    userPassword:{
        type:String,
        required:true
    }

gySchema is another schema and through patch method of https I am trying to assign a value to a variable in gySchema in Nodejs, how can I do so??

1 answer

  • answered 2021-09-27 17:41 itiDi

    Below is the code for your reference as I too have done a project using this. When your using patch you have to just use req.body as it is what you want to update. and the route will be req.patch. patch is for partial update. put is for entire update.

    model

    const Joi = require("joi");
    const mongoose = require("mongoose");
    const { Genre, validateGenre, genreSchema } = require("./genre");
    Joi.objectId = require("joi-objectid")(Joi);
    
    const movieSchema = new mongoose.Schema({
        title: {
            type: String,
            required: true,
            minlength: 5,
            maxlength: 50,
        },
        numberInStock: {
            type: Number,
            required: true,
            min: 0,
            max: 255,
            default: 13,
        },
        dailyRentalRate: {
            type: Number,
            min: 0,
            max: 255,
            required: true,
        },
        liked: {
            type: Boolean,
            default: false,
        },
        genre: {
            type: genreSchema,
            required: true,
        },
    });
    
    const Movie = mongoose.model("Movie", movieSchema);
    
    function validateMovie(movie) {
        const schema = {
            title: Joi.string().required().min(5).max(255),
            numberInStock: Joi.number().required().min(0).max(255),
            dailyRentalRate: Joi.number().required().min(0).max(255),
            liked: Joi.boolean(),
            genreId: Joi.objectId().required(),
            _id: Joi.objectId(),
        };
        return Joi.validate(movie, schema);
    }
    
    module.exports.Movie = Movie;
    module.exports.validateMovie = validateMovie;
    

    routes

    const express = require("express");
    const { Movie, validateMovie } = require("../models/movie");
    const { Genre } = require("../models/genre");
    const auth = require("../middlewares/auth");
    const admin = require("../middlewares/admin");
    const validateObjectId = require("../middlewares/validateObjectId");
    
    const router = express.Router();
    
    router.get("/", async (req, res) => {
        const movies = await Movie.find();    
        res.send(movies);
    });
    
    router.post("/", async (req, res) => {
        //validate the movie
        const { error } = validateMovie(req.body);
        if (error) {
            console.log(error);
            return res.status(400).send(error.details[0].message);
        }
    
        const genre = await Genre.findById(req.body.genreId);
        if (!genre) {
            return res.status(400).send("No genre found with given id");
        }
    
        const movie = new Movie({
            title: req.body.title,
            numberInStock: req.body.numberInStock,
            dailyRentalRate: req.body.dailyRentalRate,
            liked: req.body.liked,
            genre: {
                _id: genre._id,
                name: genre.name,
            },
        });
    
        // console.log(movies);
        await movie.save();
        console.log("Saving the document...");
        res.send(movie);
    });
    
    //updating
    router.put("/:id", async (req, res) => {
        const { error } = validateMovie(req.body);
        if (error) {
            return res.status(400).send(error.details[0].message);
        }
    
        let genre = await Genre.findById(req.body.genreId);
        console.log(genre);
        if (!genre) {
            return res.status(400).send("No genre found with given id");
        }
    
        let movieDetails = await Movie.findByIdAndUpdate(
            req.params.id,
            {
                title: req.body.title,
                numberInStock: req.body.numberInStock,
                dailyRentalRate: req.body.dailyRentalRate,
                liked: req.body.liked,
                genre: {
                    _id: genre.id,
                    name: genre.name,
                },
            }, //when using patch method, then u need not have to write this whole thing. instead just write req.body
            { new: true }
        );
    
        if (!movieDetails) {
            return res.status(404).send("No such movie details found.");
        }
    
        res.send(movieDetails);
    });
    
    router.delete("/:id", async (req, res) => {
        let movieDetails = await Movie.findByIdAndDelete(req.params.id);
    
        if (!movieDetails) {
            return res.status(404).send("No id found for given Movie");
        }
    
        res.send(movieDetails);
    });
    
    module.exports = router;
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum