简体   繁体   English

更新mongodb集合的问题

[英]problems to update mongodb collection

so I have two different collections for my social media app.所以我的社交媒体应用程序有两个不同的集合。 One for the users and the other one for the user's posts.一份用于用户,另一份用于用户的帖子。 Whenever I'm updating the info from one of my user's collection it should also modify it on the post (since my post collection includes data from the user too), but it's only doing it on the posts that I create after that and not on the ones that I've been creating before.每当我从我的用户集合中更新信息时,它也应该在帖子上修改它(因为我的帖子集合也包含来自用户的数据),但它只在我之后创建的帖子上进行而不是在我以前一直在创建的那些。 How can I fix it?我该如何解决?

USER SCHEMA用户架构

const userSchema = new Schema({
    name: { type: String, required: true },
    lastname: { type: String, required: true },
    username: { type: String, required: true },
    email: { type: String, required: true },
    password: { type: String, required: true, minlength: 8 },
    avatar: { data: Buffer, contentType: String },
});

POST SCHEMA POST SCHEMA

const postSchema = new Schema({
   user: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
   name: { type: String, required: true },
   lastname: { type: String },
   username: { type: String },
   avatar: { data: Buffer, contentType: String },
   date: { type: Date, default: Date.now() },
   textOfThePost: { type: String, required: true },
});

EDIT FUNCTION EXPRESS/MONGOOSE编辑功能快递/猫鼬

router.put("/edit_profile", async (req, res) => {
  try {
    const { name, lastname, username } = req.body;
    const user = await User.findById(req.user).select("-password");

     if (!user) return res.status(404).json("User doesn't exists");

     if (name) user.name = name;
     if (lastname) user.lastname = lastname;
     if (username) user.username = username;

     await user.save();
     res.json(user);
  } catch (err) {
     res.status(500).json({ error: err.message });
 }
 };

You can use updateMany() for that purpose.为此,您可以使用updateMany()

const res = await Post.updateMany({ user: user.id  }, { name: user.name, username: user.username /* ... */  });

However as already pointed out you are storing user data redundant on the post model as well as on the user model which is not necessary.但是,正如已经指出的那样,您将多余的用户数据存储在 post 模型以及不必要的用户模型上。 Similar to joins in SQL you can simply use populate() and not store any user-related data on your post model.类似于 SQL 中的连接,您可以简单地使用populate()并且不在您的帖子模型中存储任何与用户相关的数据。 This way everytime you query your posts it will automatically pull the latest matching user model by its id.这样,每次您查询帖子时,它都会根据其 ID 自动提取最新匹配的用户模型。

myPost.populate('user')

Note that therefore the ref is required, which tells mongoose how to populate the user field.请注意,因此ref是必需的,它告诉猫鼬如何填充用户字段。

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

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