【问题标题】:How do I update an object in Post Model from the User Model using Mongoose, Node.js and React.js?如何使用 Mongoose、Node.js 和 React.js 从用户模型更新 Post 模型中的对象?
【发布时间】:2021-10-28 14:25:35
【问题描述】:

我仍在处理这个问题,到目前为止我已经实现了我在网上看到的内容,但仍然无法正常工作。我有两个名为:PostSchema 和 UserSchema 的模型。 PostSchema 和Userschema 都有一个名为“用户名”的字段。因此,我创建了使用户能够更新其个人资料的操作。我现在面临的挑战是存储在 UserSchema 中的用户所做的更新不会反映在 PostSchema 上。例如,我希望将 PostSchema 上的用户名更新为 UserSchema 上的当前用户名是用户更新或从 UserSchema 更改他们的名称。我正在尝试在猫鼬中使用 ref 和填充功能。可能,我没有以正确的方式做这件事。 使用我现在拥有的当前代码,帖子无法获取。如果我删除 populate('username', 'username').exec() 行,它将获取但 post.username 不会更改为来自 UserSchoma 模型的 user.username。

这是我的代码: 我还是新手,还在学习,请帮助我度过这个阶段。

UserSchema 模型

const mongoose = require("mongoose"); //import mongoose

 const UserSchema = new mongoose.Schema({

    username:{  //I want the username here to update to post model too
        type: String,
        required: true,
        unique: true
    },
    email:{
        type: String,
        required: true,
        unique: true
    },
    password:{
        type: String,
        required: true
    },
    profilePicture:{
        type: String,
        default: "",
    },
 }, {timestamps: true}
);
//exporting this schema
module.exports = mongoose.model("User", UserSchema);

PostSchema 模型

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

 const PostSchema = new mongoose.Schema(
 {
   
    title:{
        type: String,
        required: true,
        unique: true
    },
    description:{
        type: String,
        required: true, 
    },
    postPhoto:{
        type: String,
        required:false,
    },
    username:{ //this should reference user.username
        type: Schema.Types.ObjectId, ref: 'User',
        required: true,
    },
    categories:{
        type: Array,
        required: false
        
    },
   
  }, {timestamps: true}
  );
 //exporting this schema
  module.exports = mongoose.model("Post", PostSchema); 

这是我收到帖子的地方

//Get Post
 router.get("/:id", async(req, res)=>{
 try{
    const post = await Post.findById(req.params.id);
    
    populate(' username', 'username').exec()
      
    res.status(200).json(post)

 }catch(err){
    res.status(500).json(err)
 }
})

这是使用 React.js 的客户端代码,我从 api 调用帖子

import { useLocation } from 'react-router';

export default function SinglePost() {
const location = useLocation()
const path = location.pathname.split("/")[2];
const [post, setPost] = useState({});
const [title, setTitle] = useState("")
const [description, setDescription] = useState("");
const [updateMode, setUpdateMode] = useState(false)


 useEffect(() => {
    
   const getPost = async () => {
       try{
        const response = await axios.get("/posts/"+path )
        setPost(response.data);
        setTitle(response.data.title);
        setDescription(response.data.description);
        setPostUser(response.data.username)


       }catch(err){

       }
   
   };       
 return getPost()
}, [path]);

【问题讨论】:

    标签: node.js reactjs mongoose


    【解决方案1】:

    使用$lookup 和聚合 聚合对象是这样的

    Post.aggregate([
          { $match: { _id: req.params.id } },
          {
            $lookup: {
              from: "User",
              localField: "username",
              foreignField: "_id",
              as: "username",
            },
          },
        ]).exec()
    

    【讨论】:

    • 好的,谢谢您的帮助。我将把这段代码放在哪里?
    • 关于集合 User 使用聚合,现在我更新我的答案
    猜你喜欢
    • 2020-12-21
    • 1970-01-01
    • 2011-06-28
    • 2012-12-13
    • 1970-01-01
    • 2018-11-09
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多