【发布时间】:2021-05-23 04:54:58
【问题描述】:
您好,我正在尝试在 mongoDB 中创建一个计算字段,但是我收到此错误: MongoError: '$add' 中的美元 ($) 前缀字段 '$add' 对存储无效。
这是代码:
router.post('/char1btn', ensureAuthenticated, function(req, res) {
const {
MongoClient
} = require("mongodb");
//Replace the uri string with your MongoDB deployment's connection string.
const uri =
'mongodb+srv://test:test1234@databasetest.5f9jh.mongodb.net/Databasetest?retryWrites=true&w=majority';
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const database = client.db("Databasetest");
const collection = database.collection("users");
//create a filter for charactername to update
const filter = {
characterimg: ""
};
// this option instructs the method to create a document if no documents match the filter
const options = {
upsert: false
};
const updateDoc = {
$set: {
health: 150,
attack: 3,
defence: 3,
endurance: 10,
characterimg: "https://i.ibb.co/MPg2SMp/Apocaliptic1.png",
},
$set: {
$add: ["$power", "$attack", "$defence", {
$devide: ["$endurance", 3]
}]
}
}
const result = await collection.updateOne(filter, updateDoc, options);
console.log(
`${result.matchedCount} document(s) matched the filter, updated ${result.modifiedCount} document(s)`,
);
} finally {
res.redirect('/main');
await client.close();
}
}
run().catch(console.dir);
})
有谁知道如何解决这个问题?
【问题讨论】:
-
您没有提供任何要设置的字段名称。
-
所以你的意思是我必须这样做: $set: $" power" { $add : [ "$power", "$attack" ,"$defence" , { $devide : ["$endurance", 3]}]} } 或者你能给我举个例子。
标签: javascript mongodb