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

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

问题描述

我正在尝试构建一个综合了AWS,MongoDB和Express属性的Vue.js应用.我使用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.

修改:

如果后端的配置方式如下

If your backend is configured in the following way

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天全站免登陆