如何使用 Vue.js、AWS Amplify 和 MongoDB 检索 currentUser 数据 [英] How to retrieve currentUser data with Vue.js, AWS Amplify, and MongoDB

查看:35
本文介绍了如何使用 Vue.js、AWS Amplify 和 MongoDB 检索 currentUser 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个 Vue.js 应用程序,它综合了 AWS、MongoDB 和 Express 的属性.我使用 aws-amplifyaws-amplify-vue 为应用程序构建了一个身份验证页面.登录应用程序后,包含已登录 AWS 用户的用户名的元数据将传递到数据对象属性 this.name 中,如下所示:

I am attempting to build a Vue.js App that synthesizes properties of AWS, MongoDB, and Express. I built an authentication page for the app using aws-amplify and aws-amplify-vue. After logging into the app, metadata containing the username for the logged in AWS user is passed into data object property this.name like so:

  async beforeCreate() {
    let name = await Auth.currentAuthenticatedUser()
    this.name = name.username
  }

this.name 然后通过 Axios 添加到 MongoDB:

this.name is then added to MongoDB via Axios:

    async addName() {
        let uri = 'http://localhost:4000/messages/add';
        await this.axios.post(uri, {
          name: this.name,
        })
        this.getMessage()
      } 

我还有一个 getName() 方法,用于从 MongoDB 中检索数据:

I also have a getName() method that I am using to retrieve that data from MongoDB:

    async getData () {
      let uri = 'http://localhost:4000/messages';
      this.axios.get(uri).then(response => {
        this.userData = response.data;
      });
    },

但是,此方法返回所有用户的数据.我想将此方法重新配置为仅返回 .currentAuthenticatedUser() 的数据.在我之前使用 Firebase 的经验中,我会使用以下内容设置我的 .getData() 方法:

This method, however, returns data for ALL users. I want to reconfigure this method to ONLY return data for .currentAuthenticatedUser(). In my previous experience with Firebase, I would set up my .getData() method with something like:

let ref = db.collection('users')
let snapshot = await ref.where('user_id', '==', firebase.auth().currentUser.uid).get()

...为了在集合中的user_id"与当前登录的 Firebase 用户匹配的情况下返回 currentUser 信息.

...in order to return currentUser information on the condition that 'user_id' in the collection matches the currently logged-in Firebase user.

为了使用 MongoDB 实现这一点,我尝试像这样配置上述方法:

To achieve this with MongoDB, I attempted to configure the above method like so:

    async getData () {
      let uri = 'http://localhost:4000/messages';
      let snapshot = await uri.where('name', '==', this.name);
      this.axios.get(snapshot).then(response => {
        this.userData = response.data;
      });
    },

我的想法是尝试通过将 MongoDB 集合中的名称"与存储在 this.name 中的登录用户进行比较来尝试返回当前用户数据...但我知道这可能不起作用,因为 .where() 方法可能是 Firebase 独有的.关于如何配置此 .getData() 以仅返回与 currentAuthenticatedUser 关联的数据的任何建议?谢谢!

My thought here was to try and return current user data by comparing 'name' in the MongoDB collection with the logged-in user stored in this.name...but I understand that this might not work because the .where() method is probably unique to Firebase. Any recommendations on how to configure this .getData() to return ONLY data associated with the currentAuthenticatedUser? Thanks!

快速路线:

const express = require('express');
const postRoutes = express.Router();

// Require Post model in our routes module
let Post = require('./post.model');

// Defined store route
postRoutes.route('/add').post(function (req, res) {
  let post = new Post(req.body);
  post.save()
    .then(() => {
      res.status(200).json({'business': 'business in added successfully'});
    })
    .catch(() => {
      res.status(400).send("unable to save to database");
    });
});

// Defined get data(index or listing) route
postRoutes.route('/').get(function (req, res) {
    Post.find(function(err, posts){
    if(err){
      res.json(err);
    }
    else {
      res.json(posts);
    }
  });
});

module.exports = postRoutes;

推荐答案

不可能将 where 子句应用于 uri AFAIK.您应该做的是将 where 子句添加到您在后端进行的实际查询中,为此,发送要用于过滤查询的 username像这样的查询参数:/messages?name=JohnDoe.

It is not possible to apply a where clause to a uri AFAIK. What you should do is adding a where clause to the actual query you are making in your backend and, to do that, send the username you want to filter the query with through a query parameter like this: /messages?name=JohnDoe.

所以基本上,如果您按照您的建议使用 Node/Express 后端,并且使用 Mongoose 作为 MongoDB 的 ODM,您的请求可能看起来像这样:

So basically if you are using a Node/Express backend, as you suggested, and using Mongoose as the ODM for MongoDB your request would probably be looking something like this:

const Users = require('../models/users.model');

Users.find({}, function (e, users) {
    if (e) {
        return res.status(500).json({
            'error': e
        })
    }

    res.status(200).json({
        'data': users
    });
})

你应该做的是通过req.query获取username查询参数,并将其添加到find 功能.

What you should do is getting the username query parameter through req.query and add it to the options in the first parameter of the find function.

const Users = require('../models/users.model');

let params = {},
    name = req.query.name;

if (name) {
    params.name = name
}

Users.find(params, function (e, users) {
    if (e) {
        return res.status(500).json({
            'error': e
        })
    }

    res.status(200).json({
        'data': users.slice
    });
})

这样,如果您指向 /messages?name=John,您将获得名称为John"的用户.

That way if you point to /messages?name=John you will get the users with "John" as their name.

编辑:

如果你的后端配置如下

postRoutes.route('/').get(function (req, res) {
    Post.find(function(err, posts){
    if(err){
      res.json(err);
    }
    else {
      res.json(posts);
    }
  });
});

你应该做的是从get方法内部获取查询参数

what you should do is get the query parameters from inside the get method

postRoutes.route('/').get(function (req, res) {
    let params = {},
        name = req.query.name

    if (name) {
       params.name = name
    }

    Post.find(params, function(err, posts){
    if(err){
      res.json(err);
    }
    else {
      res.json(posts);
    }
  });
});

这篇关于如何使用 Vue.js、AWS Amplify 和 MongoDB 检索 currentUser 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆