What is the best way to link a newly created contact to the current user in Mongoose?

I'm faced with the challenge of creating a contact that is specifically added to the current user's contact array.

Currently, my controller only creates a generic contact and doesn't cater to the individual user.

Controller:

function contactsCreate(req, res) {

  Contact
    .create(req.body)
    .then(contact => res.status(201).json(contact))
    .catch(() => res.status(500).json({ message: 'Something went wrong'}));
}

Contact Model:

const contactSchema = new Schema({

  firstName: String,
  lastName: String,
  email: String,
  job: String,
  address: String,
  number: Number
});

User model:

const userSchema = new mongoose.Schema({

  username: { type: String, unique: true, required: true },
  email: { type: String, unique: true, required: true },
  passwordHash: { type: String, required: true },
  contacts: [{ type: mongoose.Schema.ObjectId, ref: 'Contact' }]
});

Answer №1

If you have the username available in the request object, you can use the following code to successfully create a new contact:

async function addNewContact(req, res) {
  const username = req.User.username

  try {
      const newContact = await Contact.create(req.body)
      const user = await User.findOne({username})
      user.contacts.push(newContact)
      await user.save()
      return res.status(201).json(newContact)
  } catch (error) {
      return res.status(500).json({ message: 'An error occurred while adding the contact'})
  }
}

Answer №2

Big thanks to LazyElephant for the helpful input. Here is the modified solution:

const createNewContact = async (req, res) => {
  const userID = req.user.id;

  try {
    const contact = await Contact.create(req.body);
    const user = await User.findById(userID);
    user.contacts.push(contact);
    await user.save();
    return res.status(201).json(contact);
  } catch (error) {
    return res.status(500).json({ message: 'An error occurred, please try again'});
  }
}

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

An unexpected runtime error occurred due to a SyntaxError: the JSON input abruptly ended during the authentication process with the next-auth module

Encountering an Unhandled Runtime Error SyntaxError: Unexpected end of JSON input when trying to SignIn or SignOut with authentication credentials. The error is puzzling as it displays the popup error message, but still manages to register the token and s ...

What is the method used by Vue.js to establish observers in computed properties?

Consider this scenario: computed: { greeting() { const state = this.$store.state; if (state.name === 'Joe') { return 'Hey, Joe'; } else { return 'Hello, ' + state.name; } } } Which object(s) w ...

Anticipate the establishment of the database connection

I am currently in the process of waiting for the MongoDB database connection to establish. Within my code, there is a function that handles the connection process and assigns the database object to a global variable. Additionally, I have a server startup ...

Deleting a document by ObjectID in MongoDB with Node and Express without using Mongoose: A step-by-step guide

As a newcomer to backend development, I am currently using Node/Express/MongoDB with an EJS template for the frontend. I am in the process of creating a simple todo list app to practice CRUD operations without relying on Mongoose but solely native MongoDB. ...

Mastering the correct method for passing $NODE_DEBUG_OPTION to npm-run-all in IntelliJ IDEA

Running on my system with Ubuntu 16.04, I have IntelliJ IDEA Ultimate 2017.2, node v6.11.2, and npm v3.10.10. I am trying to debug a node.js application that has the following package.json start entry: "start:" "npm-run-all --parallel serve-static open-st ...

How to add suspense and implement lazy loading for a modal using Material-UI

Currently, I am implementing <Suspense /> and lazy() to enhance the performance of my project. While everything seems to be working smoothly, I have observed some minor changes in DOM handling that are causing me slight confusion. Consider this scen ...

Angular event triggered when updating input values from the model

I have developed a custom directive to add functionality to input fields with a specific class. I want to trigger events on blur and focus to update the label style based on Material Design principles. However, when using ng-model in Angular, I also need t ...

Steps to ensure that a particular tab is opened when the button is clicked from a different page

When I have 3 tabs on the register.html page, and try to click a button from index.html, I want the respective tab to be displayed. Register.html <ul class="nav nav-tabs nav-justified" id="myTab" role="tablist"> <l ...

invoking a JavaScript function from an HTML file

I want to create a JavaScript server on Raspbian that not only serves .html content to the browser but also allows for user input through events like button clicks. Both my .html and .js files are located in the same directory, and I have used absolute pat ...

I need to route the user to a specific page after they log in, depending on their role, and prevent them from accessing a certain page

Previously, I successfully implemented this functionality using Redux and MongoDB. However, when trying to achieve the same with MySQL, it is not working as expected. Currently, the logic redirects all users to the admin dashboard, but I want to implement ...

Unable to load JQuery from a div element

My goal is to create a standard .html file containing the navigation, footer, and other elements that will be used across multiple pages for a small site I'm building. I want to keep it simple and avoid using php or other programming languages. I&apo ...

sending an alert via a function's return statement

Could you explain to me why this code isn't functioning properly? When I call s.A, the alert message doesn't appear. Can you help me understand why? var s = { A: function () { alert("test A"); }, B: function () { alert("test B"); } }; ...

The data is successfully being logged in the console but is not appearing on the page in Reactjs

I'm currently working on Reactjs with the Next.js framework. I'm trying to fetch data using axios, but the data isn't showing up on the page. However, when I check the console.log in the getStaticProps section (in blogs), the data is there. ...

Get rid of the .php extension in the URL completely

Lately, I've been experimenting a lot with the .php extension. I successfully used mod_rewrite (via .htaccess) to redirect from www.example.com/example.php to www.exmaple.com/example. Everything is running smoothly. However, I noticed that even though ...

Insert a division into the table following every row

I'm working with a table that can be found here: https://codepen.io/anon/pen/bjvwOx Whenever I click on a row (for example, the 1st row 'NODE ID 1'), I want the div with the id #divTemplate to appear below that particular row, just like it d ...

The ES6 alternative to require() when not using exports

When I utilize require(./filename), I am able to include and run the code within filename without any explicit export being defined inside filename. In ES6, what is the equivalent of this using import ? Appreciate it ...

At that specific moment, a plugin is active to monitor the execution of JavaScript functions

Similar to how Fiddler allows you to monitor the communication between client and server, I am looking for a tool that can analyze all network traffic generated by client-side JavaScript on a webpage. Warm regards, bd ...

Issues arising from the use of express and CORS

I have been working on a nodejs script using express, but I am facing issues with CROS requests even after following the documentation. I set up a web server to demonstrate the problem: Despite closely following the documentation, I can't seem to fig ...

The state in a functional component in React fails to update after the initial axios call

Issue : The value of "detectLanguageKey" only updates after selecting the language from the dropdown twice. Even after selecting an option from the dropdown for the first time, the detectLanguageKey remains empty and is only updated on the second selectio ...

Fluctuation in PassportJS authentication status

I have been searching for an answer to my issue but haven't found a satisfactory solution yet. Router 1 router.post('/user', (req, res, next) => { passport.authenticate('local', function(err, user, info) { if (err) ...