【发布时间】:2020-05-27 19:24:02
【问题描述】:
因此,我正在为我的最终项目创建一个社交媒体应用程序,其中包含一个编码训练营。我们在后端使用 MongoDB/Mongoose,当他们更改用户名和名字/姓氏时,我无法尝试更新用户的数据。他们的个人资料在更新,他们在帖子中的名字在更新,但他们在其他人帖子上的 cmets 没有更新。
mongoose上的布局是这样的……
有一个用户配置文件集合。每个用户集合都有一个帖子集合(如果存在)。每个 Post 都有 Comments 集合(如果存在)。
当用户更改他们的姓名和用户名时,我正在尝试设置后端以更改他们所有帖子和所有 cmets 中的数据(最终在所有通知中)。但挑战是用户也可以在其他人的帖子上制作 cmets,所以我也需要在这些 cmets 上更改他们的名字。
这里是代码示例...
控制器:
update: function (req, res) {
db.User.findOneAndUpdate({ _id: req.params.id }, req.body, {
new: true,
})
.then(function (dbUser) {
//Updates posts from the user specified in params
//with new pic.
return db.Post.update(
{ _id: { $in: dbUser.posts } },
{
username: req.body.slug,
firstName: req.body.firstName,
lastName: req.body.lastName,
},
{ multi: true }
);
})
.then(function (req) {
db.Comment.update(
{ userId: req.body.userId },
{
$set: {
username: req.body.slug,
firstName: req.body.firstName,
lastName: req.body.lastName,
},
},
{ multi: true }
);
})
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
模型(简化):
const userSchema = new Schema({
username: { type: String, required: true },
//username in lowercase
slug: { type: String, required: true },
firstName: { type: String, required: true },
lastName: { type: String, required: true },
posts: [
{
type: Schema.Types.ObjectId,
ref: 'Post',
},
],
notifications: [
{
type: Schema.Types.ObjectId,
ref: 'Notification',
},
],
})
const postSchema = new Schema({
userId: { type: String, required: true },
username: { type: String, required: true },
firstName: { type: String, required: true },
lastName: String,
postBody: { type: String, required: true },
createdAt: { type: Date, default: Date.now },
comments: [
{
type: Schema.Types.ObjectId,
ref: 'Comment',
},
],
});
const commentSchema = new Schema({
postId: { type: String, required: true },
username: { type: String, required: true },
commentBody: { type: String, required: true },
createdAt: { type: Date, default: Date.now },
firstName: { type: String, required: true },
lastName: String,
userId: { type: String, required: true },
originalPoster: { type: String, required: true },
});
我相信数据是从前端正确发送的,因为用户帖子正在正确更新,只是帖子中的 cmets 没有正确更新。由于 cmets 是一个单独的集合,我想编写一个扫描每个评论的函数,如果 userId = req.body.userId,则更新 firstName,lastNa
【问题讨论】: