简体   繁体   English

从 mongoDB 检索用户数据

[英]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.我正在使用 mongoDB/mongoose,我刚刚阅读了有关填充方法以及在当前模式中引用其他模式的信息。 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:这是我的 userModel - 不确定是否有必要显示:

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.) (如果有人想知道为什么 model 被称为“用户”——这就是我最初偶然称它的名字,当我将名称更改为“用户”时它出错了......所以我把它改回来了。)

I am not sure how to add the userId when making an instance of the groceryListItem .我不知道在创建groceryListItem实例时如何添加userId In the mongoose docs ( https://mongoosejs.com/docs/populate.html#saving-refs ), they use the example of a Story and Person Schema.在 mongoose 文档( https://mongoosejs.com/docs/populate.html#saving-refs )中,他们使用了故事和人物模式的例子。 They reference each other, and then they create an instance of Person, calling it author.它们相互引用,然后创建 Person 的一个实例,称为作者。 Then they grab the _id from author and reference it in their instance of Story, called story1.然后他们从作者那里获取 _id 并在他们的 Story 实例中引用它,称为 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.但他们能做到这一点的唯一方法是因为 author 和 story1 位于同一个文件中。

So it seems like what I should do is grab the user _id by saying userId: users._id .所以看起来我应该做的是通过说userId: users._id来获取用户 _id 。 But my new User instance is in my user routes.但是我的new User实例在我的用户路由中。 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:编辑 - 前端 API 调用:

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: "" });
  };

Here you can simply pass in the user ID in the POST request params.在这里,您可以简单地在 POST 请求参数中传入用户 ID。 The POST URL in the frontend should look like this;前端的 POST URL 应该是这样的; { localhost:9000/like/${userID} } { localhost:9000/like/${userID} }

You can get the user ID at the express backend like this;您可以像这样在 express 后端获取用户 ID;

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);

}); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM