What is the process for combining two mongodb collections in a mongoose controller route?

Hello, I am relatively new to node.js and express. I am currently working on setting up a mongoose schema to allow users to create characters and store them in the associated collection with that user. I have two schemas in place, one for users and one for characters.

So far, I have experimented with using .populate and pushing into the user array within my character schema. However, I haven't been able to achieve the desired results yet.

Below are my schema definitions and route file for creating a new user and character. I am unsure of how to link the newly created character to its corresponding user without overriding any existing character IDs already stored.

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const characterSchema = new Schema({
    name: {
        type: String,
        required: true,
    },
    job: {
        type: String,
        required: true,
    },
    race: {
        type: String,
        required: true,
    },
    level: {
        type: String,
        required: true,
    },
    image: {
        type: String,

    },
    user: [{
        type: schema.Types.ObjectId,
        ref: 'User'
    }]

});

const Character = mongoose.model('Character', characterSchema);
module.exports = Character;
const Schema = mongoose.Schema;


const userSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
    },
    password: {
        type: String, 
        required: true,

    },
    date: {
        type: Date,
        default: Date.now
    }

});

const User = mongoose.model('User', userSchema);

module.exports = User;



router.route('/').get((req, res) => {
    User.find()
        .then(users => res.json(users))
        .catch(err => res.status(400).json("Error" + err))
    });


    router.route('/:id').get((req, res) => {
        User.findById(req.params.id)
            .then(user => res.json(user))
            .catch(err => res.status(400).json("error" + err))
    })


router.route('/character').get((req, res) => {
    Character.find()
        .then(characters => res.json(characters))
        .catch(err => res.status(400).json("error" + err))
})


router.route('/character').post((req, res)=> {
    const newCharacter = new Character({
        name: req.body.name,
        job: req.body.job,
        race: req.body.race,
        level: req.body.level
    })
    newCharacter
    .save()
    .then(character => res.json(character))
    .catch(err => res.status(400).json("error" + err));
})

Answer №1

Although I am not an expert in node.js or mongoose, I do have some experience with them.

To me, it seems a bit strange because I believe you should be using a reference to the character from the user, unless I am misunderstanding something. After all, a user typically has a character associated with them.

When handling this situation:

If a user creates a character and posts it, you would need to retrieve the user by cookie, id, or other means and then update the character accordingly.

It might look something like this:

User.findOneAndUpdate(
    { "_id": userID},
    { 
        "$set": {
            "character.$": character
        }
    },
    function(err,doc) {

    }
);

Therefore, I believe this part is missing in the UserModel:

   character: [{
        type: schema.Types.ObjectId,
        ref: 'Character'
    }]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering issues with npm-adduser when trying to input credentials for npm account

After developing an npm package on one machine, I cloned it to a different machine and encountered an error when trying to run npm publish: npm ERR! need auth auth and email required for publishing npm ERR! need auth You need to authorize this machine usi ...

Steps to establish a connection with a remote MYSQL database using the actual IP address in Node.js

In my Nodejs file, I have set up the connection as follows. The issue arises when attempting to connect to the remote database on a server. module.exports = { host: '234.32432.32432',//this is an example IP address and not a real one. use ...

Tips for creating a tailored Express.js request interface using Typescript efficiently

I have been working on designing a custom Express request interface for my API. To achieve this, I created a custom interface named AuthRequest, which extends Request from Express. However, when attempting to import my interface and define req to utilize t ...

Encountering an error while attempting to publish content on a different domain

Currently, I am attempting to send data in form-urlencoded format using Axios. Below is the code snippet: const qs = require("qs"); const axios = require("axios"); const tmp = { id: "96e8ef9f-7f87-4fb5-a1ab-fcc247647cce", filter_type: "2" }; axios .po ...

Error: The TypeScript aliases defined in tsconfig.json cannot be located

Having trouble finding the user-defined paths in tsconfig.json – TypeScript keeps throwing errors... Tried resetting the entire project, using default ts configs, double-checked all settings, and made sure everything was up-to-date. But still no luck. H ...

Eliminating a particular tag along with its corresponding text - cheeriojs

Is there a way for me to remove a particular tag and its content from the HTML file I am scraping? I need help in searching for and deleting this specific tag and text altogether. <p class="align-left">&#xA0; Scheduled Arrival Time</p> ...

transforming objects into dynamic pathways

In my application, I have an object structure that represents my controllers: { api: { test: function () {} }, routes: { docs: { options: function () {}, usage: function () {} }, index: f ...

Selecting DigitalOcean city based on user location in Node.js

Currently, I am implementing Node.js in conjunction with my HTTP server. My goal is to have every user who connects to the server be linked to a real-time game server through WebSockets. Furthermore, I aim for users to automatically connect to the nearest ...

The installation process of NPM within a Docker container encounters difficulties, whereas it successfully executes on the host machine with

I am currently deploying node.js services to a corporate system using docker containers. The Dockerfiles for these services are quite simple, except for the fact that I need to set some proxy environment variables: FROM node:4.2.3 ADD . /src WORKDIR /sr ...

How can I modify an array in Couchbase by using an N1QL query?

{ "name":"sara", "emailId":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abcde8e2ea9627225c4b9a3afa7bbcc808cb554a1adaf">[email protected]</a>", "subjects" : [{ "name":"Math", "tutor":"alice", "classes" ...

Tips for troubleshooting ECONNRESET error in socket.io and express during a Nessus scan

I keep running into ECONNRESET errors that are causing my node server to crash when I initiate a basic network scan using Nessus Essentials: node:events:505 throw er; // Unhandled 'error' event ^ Error: read ECONNRESET at TCP.onS ...

Create a pipeable stream that does not trigger any events when data is piped

I have been trying to utilize the renderToPipeableStream function from React18, and although it is functional, I am struggling with handling the pipe properly. The key section of my code involves an array of strings representing HTML. I am splitting the s ...

Executing the command "npm audit fix" will result in the installation of an outdated package

After running npm audit, I received a report on vulnerabilities: react-dev-utils 0.4.0 - 12.0.0-next.60 Severity: critical Issue: Improper Neutralization of Special Elements used in an OS Command. Dependencies at risk: - browserslist - fork-ts-checker-web ...

Is there a way to update a bot's nickname in Discord.js without constantly triggering the message/messageCreate event every minute?

Is there a way to automatically change the bot nickname every minute without relying on events? I attempted using message.guild.members.cache.get(bot.user.id).setNickname("Botnickname" + "✅") and message.guild.me.setNickname("Botnme" + "✅"), but it onl ...

Protect the endpoints of my ExpressJS server by ensuring they can only be accessed through secure cURL requests

Hello, I'm seeking some guidance on how to restrict access to specific routes on my server to only certain users. Currently, my server has some straightforward routes such as "/example" and I am using Express JS to define these routes. The individual ...

Dealing with audio bleed from a previous recording using fluent-ffmpeg

const Discord = require('discord.js'); const client = new Discord.Client(); const ffmpegInstaller = require('@ffmpeg-installer/ffmpeg'); const ffmpeg = require('fluent-ffmpeg'); ffmpeg.setFfmpegPath(ffmpegInstaller.path); co ...

Working with JSON data and extracting specific information within the grades

Here is a JSON data structure that contains information about a student named Alice and her grades in various courses: { "student": [{ "cert_id": "59826ffeaa6-b986fc04d9de", "batch_id": "b3d68a-402a-b205-6888934d9", "name": "Alice", "pro ...

Is there a way to receive a comprehensive report in case the deletion process encounters an error?

Currently, I am performing a delete operation with a filter based on 2 fields: const query = await Flow.deleteOne({ _id: flowId, permissions: currentUser!.id, }); After executing the delete operation, I inspect the query object to determine its su ...

Is the user consistently experiencing redirection to a failure page with passport?

I've been struggling with the user login redirection issue on my website. No matter what changes I make, it keeps redirecting to failure instead of success. I'm not sure if I missed something or did something wrong. The documentation for passport ...

Obtain the value of a key from a collection of JSON objects using NodeJS

I'm dealing with a JSON object that is presented as a list of objects: result=[{"key1":"value1","key2":"value2"}] In my attempts to extract the values from this list in Node.js, I initially used JSON.stringify(result) but was unsuccessful. I then tr ...