user12786932
user12786932

Reputation:

Retrieving user data from mongoDB

I'm building an app where a user logs in and can create a grocery list on their account (there are more things they can do like create recipes, but this is the example I want to use). Right now I have it so everybody who logs in sees the same list. But I want each user to be able to log in and view their own grocery list that they made. I'm assuming the logic is literally like logging into a social media site and viewing YOUR profile, not somebody else's.

I'm using mongoDB/mongoose and I just read about the populate method as well as referencing other schemas in your current schema. Here is my schema for the list:

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

// Create item schema
const GroceryListItemSchema = new Schema({
  item: {
    type: String,
    required: [true, 'Item field is required']
  },
  userId: {
    type: mongoose.Schema.Types.ObjectId, ref: "user",
  }
});


// Create an Item model
const GroceryListItem = mongoose.model('groceryListItem', GroceryListItemSchema);
module.exports = GroceryListItem;

And here is the post request to add a list item:

//POST request for shopping list
router.post("/list", checkToken, (req, res, next) => {
  // Add an item to the database
  const groceryListItem = new GroceryListItem({
    item: req.body.item,
    userId: ???
  })

  groceryListItem.save()
    .then((groceryListItem) => {
      res.send(groceryListItem);
    })
    .catch(next);
});

Here is my userModel - not sure if this is necessary to show:

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

const UserSchema = new Schema({
  username: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  password2: {
    type: String,
    required: true,
  },

});

const User = mongoose.model("users", UserSchema);
module.exports = User;

(in case anyone is wondering why the model is called "users"-- that's what I initially called it on accident and when I changed the name to "user" it errored out...so I changed it back.)

I am not sure how to add the userId when making an instance of the groceryListItem. In the mongoose docs (https://mongoosejs.com/docs/populate.html#saving-refs), they use the example of a Story and Person Schema. They reference each other, and then they create an instance of Person, calling it author. Then they grab the _id from author and reference it in their instance of Story, called story1. So that makes sense to me. But the only way they can do that is because author and story1 are located in the same file.

So it seems like what I should do is grab the user _id by saying userId: users._id. But my new User instance is in my user routes. And I'd rather not combine the two. Because then I'd have another list to combine as well so that would be my user routes, recipe routes, and shopping list routes all in one file and that would be extremely messy.

Anyone have any idea how I can make this work? It seems so simple but for some reason I cannot figure this out.

Thank you!!

EDIT - frontend API call:

handleSubmitItem = (e) => {
    e.preventDefault();
    const newItem = {
      item: this.state.userInput,
    };

    authAxios
      .post(`http://localhost:4000/list/${userId}`, newItem)
      .then((res) => {
        this.setState({ items: [...this.state.items, newItem] });
        newItem._id = res.data._id;
      })
      .catch((err) => console.log(err));

    this.setState({ userInput: "" });
  };

Upvotes: 0

Views: 43

Answers (1)

Joshua Oweipadei
Joshua Oweipadei

Reputation: 167

Here you can simply pass in the user ID in the POST request params. The POST URL in the frontend should look like this; {localhost:9000/like/${userID}}

You can get the user ID at the express backend like this;

router.post("/list/:id", checkToken, (req, res, next) => {
// Add an item to the database
const groceryListItem = new GroceryListItem({
    item: req.body.item,
    userId: req.params.id
})

groceryListItem.save()
    .then((groceryListItem) => {
        res.send(groceryListItem);
    }).catch(next);

});

Upvotes: 0

Related Questions