node.js - 从集合返回的重复项目
问题描述
博客架构:
{
body: { type: String, required: true },
title: { type: String, required: true },
published: { type: String, default: false },
date: { type: Date, default: Date.now },
user: { type: Schema.Types.ObjectId, ref: 'BlogUser' },
comments: [{ type: Schema.Types.ObjectId, ref: 'Comments' }],
likes:[{user:{ type: Schema.Types.ObjectId, ref: 'BlogUser' }}]
}
Like Route 用于添加点赞:
exports.likeBlog = async (req, res) => {
const blog_id = req.params.blog_id;
const user_id = req.body.user_id;
await Blog.findByIdAndUpdate(
blog_id,
{
$push: {
likes: {
user: user_id,
},
},
},
{ new: true },
(err, newBlog) => {
if (err) res.status(422).json(err);
console.log(newBlog);
res.json(newBlog);
}
);
};
接收博客的博客路径:
exports.getBlogByID = async (req, res) => {
const blog_id = req.params.blog_id;
try {
const blog = await Blog.findById(blog_id)
.populate("comments")
.populate("user");
console.log(blog);
res.json(blog);
} catch (error) {
res.status(401).json(error);
}
};
当我通过从客户端调用添加一个喜欢时Like route
,我得到一个具有正确数量的博客,即只有 1 个。但是当我从它请求博客时, Blog Route
它返回我在“喜欢”数组中的两个对象,它们彼此相同(相同的 id也)。为什么我会得到这样的结果?请注意,我在调用“Like Route”之后调用了“Blog Route”。
解决方案
在我将“like route”更改为此之后,它运行良好:
exports.likeBlog = async (req, res) => {
const blog_id = req.params.blog_id;
const user_id = req.body.user_id;
const blog = await Blog.findById(blog_id);
blog.likes.unshift({ user: user_id });
await blog.save();
Blog.findById(blog_id)
.then((result) => {
res.json(result);
})
.catch((error) => {
res.status(501).json({ error });
});
};
我仍然不知道两者之间有什么区别。
推荐阅读
- ios - 如何在 Ionic/Cordova 构建中正确引用 iOS 3rd 方框架,使其不会抛出 dyld:未加载库:@rpath 错误
- git - 合并从本地分支发送到主分支的请求,同时将一些更改推送到本地分支
- bash - 从 MATLAB 调用 Anaconda 环境:未找到 Conda 命令
- c# - SQL - 使用分组方式选择,从具有最大值(日期)的寄存器中获取数据
- android - 我的回收站视图未显示任何 Firebase 图像
- ios - 是否可以通过互联网将 Xcode 与 iPhone 连接起来进行开发?
- lua - 对于 for 循环中两个索引的新索引
- graphics - 有没有办法摆脱低FOV影响的1点透视部分?
- ios - 为 UISegmentedControl 添加边框
- android - Android Studio 3.6 无法点击文本来更改其 ID 和文本