Javascript 如何使用$inc增加MongoDB集合中的属性
我有一个文章列表,其中包含一个属性Javascript 如何使用$inc增加MongoDB集合中的属性,javascript,node.js,reactjs,mern,Javascript,Node.js,Reactjs,Mern,我有一个文章列表,其中包含一个属性views,我想在用户每次单击文章标题时在数据库中增加该属性。目前,当我这么做的时候,什么都没有发生。为什么它不工作?我如何在每次单击时增加该属性?以下是我的反应部分: const incrementViews = (id) => { var item = posts.find(x => x._id === id); item.views += 1; } <div className=&
views
,我想在用户每次单击文章标题时在数据库中增加该属性。目前,当我这么做的时候,什么都没有发生。为什么它不工作?我如何在每次单击时增加该属性?以下是我的反应部分:
const incrementViews = (id) => {
var item = posts.find(x => x._id === id);
item.views += 1;
}
<div className="post-title">
<Link to={`/post/${post._id}`}>
<h2><a href="#" onClick={() => incrementViews(post._id)}>{post.title}</a>
</h2>
</Link>
</div>
我认为前端和后端分别存在两个问题
- 前端
您应该使用
变量作为状态变量,以便在post
上进行更改时重新呈现then组件post
- 后端
增加代码中的
没有问题 在这里,您需要返回成功状态视图
incrementViews
只增加前端的视图,从不向API发送任何数据。您可以通过以下方式使其工作:
server.js
itemRoutes.route(“/increment/:id”).post(异步(req,res)=>{
const{id}=req.params;
updateOne({u id:id},{$inc:{views:1}});
返回res.status(200).json({msg:“OK”});
});
:
//注意:id,冒号很重要。
itemRoutes.route(“/increment/:id”).post(异步(req,res)=>{
const{id}=req.params;
// ...
});
。删除了数据库逻辑,只添加了响应消息。
我用邮递员测试了演示,效果很好
在向POST请求时https://adaptive-sassy-legal.glitch.me/increment/123
,应返回如下所示的响应
{
消息:“项目路由增量。”,
身份证号码:“123”
}
更新2
在上一次更新中我忘记提到的另一件事是更新中间件
//仅使用`/increment`而不是`/increment/:id`。
应用程序使用(“/increment”,itemRoutes);
.像这样归还还是?:itemRoutes.route('/increment').post(async(req,res)=>{var increment=collection.updateOne({{u id:id},{$inc:{views:1});返回res.status(increment);});您应该返回200状态,而不是
增量
。因此返回res.status(200).send('Success')
我得到了这个错误:根据您的服务器.js
,POST 404(未找到),应该是正确的路由,但这也不起作用。如果你能用你的服务器代码更新问题,我可以帮你。你好,我用整个服务器代码更新了我的问题。hi@JayRobertson,我已经更新了答案并添加了一个演示。试一试。嗨,@kasipavankumar我添加了缺失的冒号,但我仍然得到了相同的错误:POST-astrogic-backend.herokuapp.com/5ea16d7de7179a52a762d633 404(未找到)。
// Requiring the dependencies
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv').config();
const mongoose = require('mongoose');
const PORT = process.env.PORT || 3001;
const BASE_URL = process.env.REACT_APP_BASE_URL;
console.log(BASE_URL)
const itemRoutes = express.Router();
let Comment = require('./comment.model');
app.use(cors());
app.use(bodyParser.json());
mongoose.connect(BASE_URL, { useNewUrlParser: true })
const connection = mongoose.connection;
connection.once('open', function () {
console.log('Connection to MongoDB established succesfully!');
});
let collection = connection.collection("posts_with_tags_test");
collection.createIndex(
{
postContent: 'text',
title: 'text'
}
);
// Serve static assets
if (process.env.NODE_ENV === 'production') {
app.use(express.static('build'));
}
itemRoutes.route('/').get(async (req, res) => {
let collection = connection.collection("posts_with_tags_test");
let response = await collection.find({})
.toArray();
res.send(response);
});
itemRoutes.route('/search').post(async (req, res) => {
let result = await connection.collection("posts_with_tags_test").find({
$text: {
$search: req.body.searchString
}
}).toArray();
res.send(result);
});
itemRoutes.route("increment/:id"").post(async (req, res) => {
const { id } = req.params;
collection.updateOne({ _id: id }, { $inc: { views: 1 } });
return res.status(200).json({ msg: "OK" });
});
itemRoutes.route('/comments').get(async (req, res) => {
let collection = connection.collection("comments");
let response = await collection.find({})
.toArray();
res.send(response);
});
itemRoutes.route('/comments')
.post((req, res) => {
res.setHeader('Content-Type', 'application/json');
let comment = new Comment(req.body);
comment.save()
.then(comment => {
res.status(200).json({ comment })
})
.catch(err => {
res.status(400).send('failed')
})
});
app.use('/', itemRoutes);
app.use('/comments', itemRoutes);
app.use('/search', itemRoutes);
app.use('/increment', itemRoutes);
app.listen(PORT, function () {
console.log('Server is running on' + ' ' + PORT);
})
const incrementViews = (id) => {
// Assuming your API server is running on port 5000.
fetch(`http://localhost:5000/increment/${id}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
})
.then((res) => res.json())
.then(console.log)
.catch(console.error);
};