【问题标题】:Finding a user and adding an id to its friends array property查找用户并将 id 添加到其好友​​数组属性中
【发布时间】:2020-10-31 17:34:16
【问题描述】:

当点击“关注用户”按钮(在 Frienddetail 组件中)时,会调用 addPeopleFollow 函数。使用此功能,我想将单击的用户(您尝试关注的用户)的 ID 存储在登录/单击我的数据库的用户的 Friends Array 属性中。

我的数据库有一个用户集合,其中所有用户都在每个用户中:

_id:5eff397b70d78284c8c45186
friends:Array
username:"charlestryingout"
password:"$2b$10$CYMyPx10gk0jO5XoazcrSO32Ng37qoyU6uXkkeaswQ5KWm7k7ooym"
__v:0

例如:如果 id = 5eff397b70d78284c8c45186 的用户点击另一个用户以跟随 id = 5eff397b70d78284c8c45187,那么我希望在我的数据库中得到这个结果:

_id:5eff397b70d78284c8c45186
friends:Array[5eff397b70d78284c8c45187]
username:"charlestryingout"
password:"$2b$10$CYMyPx10gk0jO5XoazcrSO32Ng37qoyU6uXkkeaswQ5KWm7k7ooym"
__v:0

我已经对 addPeopleFollow 函数(axios 请求)的内容进行了编码,并设法让它工作(我可以在控制台中的 .then 中看到 console.logs)。如果您认为它不完整,请随时提出更改建议。


我的问题:

谁能帮我写后端(下面的第一个版本)? 我首先需要在我的用户列表中搜索当前登录的用户(通过 getUser 函数,这应该可以工作)。当找到该特定用户时,我必须在其朋友数组属性中添加 id。我的第一个想法是 .findByIdAndUpdate({_id:iduser}) 但我不知道如何将 id 推送到现有的朋友数组中(更新部分)。

能否请您写出完整的代码(只考虑后端,但也可以随意建议前端的更改。我使用的是 Node/Mongoose/MongoDB/React


前端反应

addPeopleFollow(idpeopleyoufollow){
    Axios({
        method: "POST",
        url: `${process.env.REACT_APP_API_BASE}/friends`,
        data: qs.stringify(idpeopleyoufollow),
        headers: {"content-type": "application/x-www-form-urlencoded"},
        withCredentials: true
    })
    .then(() => {
        console.log("charles")
        console.log(idpeopleyoufollow)
        console.log("charles")
    })
    .catch((error) => {
        console.log(error.response)
    })
}
    
render() {
    return (
        <DefaultLayout>
        <div className="friendsoverviewcontainer">
            <h1>Our community ({this.state.friends.length} registered users)</h1>
            <form className="friends">               
                <div className="titlepart">
                    <label className="friendlabel" htmlFor="friend">Search for Users :</label><br></br>
                    <input className="friendform" type="text" name="friend" value={this.state.friend} placeholder="Type a username here!" onChange={this.searchFriends}></input>
                </div>
            </form>

            <div className="friendsboxes" >
                {
                    this.state.searchFriends.map(friend =>
                        <div key={friend._id}>
                            <Frienddetail 
                                key={friend._id}
                                id={friend._id}
                                username={friend.username}
                                location={friend.location}
                                innerCircle={this.addToInnerCircle}
                                peopleFollow={this.addPeopleFollow}
                            />
                        </div>
                    )   
                }
            </div>
        </div>

特定的Frienddetail组件

import React from 'react'
import './Frienddetail.css'

class Frienddetail extends React.Component {
    constructor() {
        super()

        this.state = {
            
        }
    }

    render() {
        return (
                <div className="friendbox">
                    <img className="imagedaredevilspicdetail" src="/images/profileimage.png" alt="picturesetting" />
                    <p className="friend">{this.props.username}</p>
                    <p className="friend">{this.props.location}</p>
                    <button className="followbutton" onClick={(e) => this.props.peopleFollow(this.props.id)}>Follow user!</button>
                    <button className="friendbutton" onClick={(e)=> this.props.innerCircle(this.props.id)}>Add to inner circle!</button>
                </div>
        )
    }
}

export default Frienddetail

用户模型

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

const userSchema = new Schema({
    username: String,
    password: String,
    location: String,
    imageUrl: String,
    friends: [String],
    error: String
})

const User = mongoose.model("users",userSchema)

module.exports = User;

后端

// add peopleYouFollow
router.post("/friends", (req,res) => {
  console.log("thisishappening")
  let iduser = getUser()._id 
  User
  .findByIdAndUpdate({_id:iduser})
  .then((response) => {
    res.json(response)
    console.log("thisishappening")
  })
  .catch(error => {
    res.json(error)
  })
})

【问题讨论】:

    标签: javascript node.js reactjs mongodb mongoose


    【解决方案1】:

    首先,我想建议对Schema 进行一些更改,因为您正在存储Array of String,您应该存储Array of ObjectId,因为您正在存储objectId _id,您可以像这样更改您的架构

    const mongoose = require("mongoose")
    
    const userSchema = new Schema({
        username: String,
        password: String,
        location: String,
        imageUrl: String,
        friends: [mongoose.Schema.Types.ObjectId],
        error: String
    })
    

    您可能必须删除您的收藏并重新构建它。

    我不确定您是否收到了这两个 ID,如果没有,您可能需要更新您的 axios 请求以发送所有数据。假设您同时收到 ID's 并且无法向 friends 数组添加任何内容?

    那是因为您没有在数组中添加任何内容,为此您需要像这样使用$push 运算符-

     router.post("/friends", (req,res) => {
      let iduser = getUser()._id 
      User.update({_id:iduser},{$push:{friends: ID of Friend here!}})
      .then((response) => {
        res.json(response)
      })
      .catch(error => {
        res.json(error)
      })
    })
    

    我没有浏览你所有的代码,因为你发布的太多了,但这就是你要找的要点!

    【讨论】:

    • 谢谢你!只是一个额外的小问题。如何访问“朋友的 ID”? req.body.id?我在前端将它作为 idpeopleyoufollow 传递,但不知道如何在后端捕获它?
    • 对此有什么想法吗?
    • 如果您可以从前端发布您在后端获取的对象,那么我可以提出一些建议,否则很难猜测
    • 我怎样才能知道我在后端得到了什么对象?
    • router.postconsole.log(req.body)
    猜你喜欢
    • 1970-01-01
    • 2021-12-07
    • 2020-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    相关资源
    最近更新 更多