node.js - 如何使用 Node.JS 对 MongoDB 中的变量使用 $inc 运算符
问题描述
我正在尝试使用我网站的 Node.JS 后端在 mongoDb 中构建“访问者数量”集合。前端将以下信息作为 JSON 发送到 Node.JS 后端。
- isUniqueVisitor - 如果是,则为 1,如果不是,则为 0
- country - 标准国家代码 - “JP”、“IN”、“UK”等
我的数据库如下所示
{
"today": 2019-06-07,
"uniqueVisitors": {
"count": 230,
"countries": {
"JP": 102,
"IN": 88,
"UK": 30
}
}
}
如果我使用具有固定值的 $inc 效果很好
Eg. $inc: {count: 1} // for string/integers keys
Eg. $inc: {"uniqueVisitors.count": 1} // inside quotes to access key of a JSON
主要问题: 我无法使用变量访问文档名称。
Eg. $inc: {`uniqueVisitors.countries[${req.body.country}]`}
这会产生错误,因为反引号不能用于 Mongo。我试过了
Eg. $inc: {uniqueVisitors["countries"][req.body.country]}
但即使这样也会产生错误。
跟着网上,发现mongo $set 使用变量可以通过将需要的JSON直接传给$set来实现。因此,我采用以下方式对其进行编码。
mongoClient.connect(mongoURL, async function (err, db) {
if (err) throw err;
console.log("Database connected");
// Identifying my document with today's date
var myQuery = {
date: getTodayDate()
};
// Defining the JSON to be passed to uniqueVisitors $inc
var uniqueVisitorsInc = {
"uniqueVisitors": {
"count": 0,
"countries": {}
}
};
// Populating the JSON to be passed to uniqueVisitors $inc => essentially asking to increase count by 1 and increase that country's count by 1
uniqueVisitorsInc["uniqueVisitors"]["count"] = 1;
uniqueVisitorsInc["uniqueVisitors"]["countries"][myData.country] = 1;
var newValues = {
$inc: uniqueVisitorsInc
};
await db.collection("visitorStats").update(myQuery, newValues, {upsert: true});
db.close();
});
上述方法在编辑器上运行良好,但引发以下运行时错误:
$inc requires numerical values
基本上要求我以 {var1: 1, var2: 5} 模式将值传递给 $inc。
请帮助我绕过这种奇怪的情况。
我知道我可以做一个两步过程,我首先读取值,增加变量并在 Mongo 中设置它。
但是有谁知道如何使用 $inc 来克服这种情况?
解决方案
如果此更新被硬编码为仅更新“JP”,则它需要如下所示:
$inc: { "uniqueVisitors.country.JP": 1 }
因此,您几乎可以使用反引号方法,但稍微更改语法并保持: 1
部分如下:
$inc: { [`uniqueVisitors.country.${req.body.country}`]: 1 }
推荐阅读
- python - 在 Python3 Flask Jinja2 模板中使用来自用户输入的参数调用函数
- powerbi - 使用条件筛选的 Power BI 度量
- python - flask-sqlalchemy:如何管理 SQL 视图?
- css - CSS/“完全”同一类的优先级较低
- python - WxPython ScrolledWindow 滚动条 - 如何使明显更大?
- python - 无法在 django 中的 url 末尾剪切斜线
- python - 如何在python中附加/连接不相关的数据帧
- python - 如何从 PDF 内容中提取(十六进制编码)文本?
- android - 从考虑android中删除状态栏
- android - 如何在 kotlin 中添加日历标题