Push item to array from one Schema to another

Viewed 50

I am just starting to learn backend-development and focusing on nodeJS with express and mongoose.

As a starter project I am trying to get a joke application to work.

What I am having issues with is I have a userSchema and a jokesSchema, where I want users to be able to save jokes from the jokesSchema and I can't get this to work.

This is my: User.Model.js

import mongoose from 'mongoose'
const {Schema} = mongoose

const userSchema = Schema({
    username: {
        type: String,
        unique: true,
        allowNull: false,
        required: true,
        lowercase: true,
        minlength: 5,
        maxlength: 20
    },
    password: {
        type: String,
        required: true,
        allowNull: false,
        lowercase: true,
        minlength: 5,
        maxlength: 20
    },
    savedjokes: [{
        type: mongoose.Schema.Types.ObjectId, 
        ref: 'jokes'
    }]
})

const UserModel = mongoose.model('user', userSchema)

export default UserModel

This is my Jokes.Model.js:

import mongoose from 'mongoose'
const {Schema} = mongoose

const jokesSchema = Schema({
    joke: {
        type: String,
        unique: true,
        allowNull: false,
        required: true,
    }
})

const JokesModel = mongoose.model('jokes', jokesSchema)

export default JokesModel

This is my: User.Controller.js

const saveJoke = async (request, response) => {
    const data = {
        $push: {
            savedjokes: [
                {
                    joke: request.body.joke,
                },
            ],
        },
    };
    try {
        const databaseResponse = await UserModel.findByIdAndUpdate(request.params.userId, data, {new: true, safe: true, useFindAndModify: false, upsert: true});
        response.status(StatusCode.OK).send(databaseResponse);
    } catch (error) {
        response.status(StatusCode.INTERNAL_SERVER_ERROR).send({message: error.message});
    }
};
0 Answers
Related