Here is my ajax code:
这是我的ajax代码:
$(function () {
$("#upvoteClick").click(function () {
$.ajax({
type:"POST",
data: {upvote: 2},
dataType: 'json',
url:"http://localhost:9000/api/upvote"
}).success(function (data) {
console.log(data);
console.log('Process success');
})
})
});
Here is my post handler in express
这是我在快递中的邮政处理程序
var express = require('express');
var postDB = require("./data/postDB");
var router = express.Router();
module.exports = router;
router.post('/upvote', function (req, res, next) {
var data = req.body.upvote;
postDB.connect
.then(db => db.posts.findAndModify({
query: {title: "Will this work"},
update: {$inc: {upvote: data}},
new: true})
.then(() => res.sendStatus(200))
.catch(next));
console.log('process SHOULD be done');
});
Picture of the post in the db
数据库中的帖子的图片
数据库中的帖子的图片
here is my postDB code which connect to my db
这是我的postDB代码连接到我的数据库
var MongoClient = require("mongodb").MongoClient;
var mongoose = require("mongoose");
var url = "mongodb://localhost:27017/crowddistdb";
var connect = MongoClient.connect(url);
mongoose.Promise = global.Promise;
mongoose.createConnection(url);
var Post = require("../admin/postModel");
module.exports = {
connect,
Post,
close: function () {
connect.then(db => db.close());
mongoose.disconnect();
}
};
I am successfully getting the number in the 'data' variable from AJAX to Express but there is something wrong with my Mongo code. I have the almost exact same way of connecting to my db and filtering through the docs in other places so i am super confused why it isnt working here.
我成功地将'data'变量中的数字从AJAX变为Express,但是我的Mongo代码有问题。我有几乎完全相同的方式连接到我的数据库并通过其他地方的文档过滤所以我非常困惑为什么它不在这里工作。
Not sure if this helps, but my POST call registers as still 'pending' in chrome dev tools.
不确定这是否有帮助,但我的POST调用在chrome dev工具中注册为“待定”。
Any help is much appreciated!!
任何帮助深表感谢!!
2 个解决方案
#1
0
You can update the current value using this
您可以使用此更新当前值
postDB.connect
.then(db => db.posts.update(
{title: "Will this work"},
{$inc: {upvote: 1}},
{new: true})
.then(() => res.sendStatus(200))
.catch(next));
#2
0
The call to findAndModify
should look something like following:
对findAndModifys的调用应该如下所示:
postDB.connect
.then(db => db.posts.findAndModify(
{title: "Will this work"},
{},
{$set:{$inc: {upvote: data}}},
{new: true})
.then(() => res.sendStatus(200))
.catch(next));
#1
0
You can update the current value using this
您可以使用此更新当前值
postDB.connect
.then(db => db.posts.update(
{title: "Will this work"},
{$inc: {upvote: 1}},
{new: true})
.then(() => res.sendStatus(200))
.catch(next));
#2
0
The call to findAndModify
should look something like following:
对findAndModifys的调用应该如下所示:
postDB.connect
.then(db => db.posts.findAndModify(
{title: "Will this work"},
{},
{$set:{$inc: {upvote: data}}},
{new: true})
.then(() => res.sendStatus(200))
.catch(next));