我试图从表单更新MongoDB Atlas集合上的文档。
我使用Node.js,MongoDB驱动程序和bodyParser。
app.post("/quotes", (req, res) => {
client.connect(err => {
const db = client.db("test");
const userID = {$eq: {"userID" : (req.body.userID)}}
const update = {$set: {"name": (req.body.name)}}
db.collection("customers").updateOne(userID, update, function(err, res) {
console.log("POST /quotes");
client.close();
});
});
res.redirect("/user");
});
他们的预期输出是我收藏中的更新文档,但实际输出在我的控制台日志中。
我的控制台日志:
the options [servers] is not supported
the options [caseTranslate] is not supported
the options [dbName] is not supported
the options [srvHost] is not supported
the options [credentials] is not supported
答案 0 :(得分:0)
req.body中的userId类型为String,那么您必须将其转换为ObjectId
const mongo = require('mongodb');
app.post("/quotes", (req, res) => {
client.connect(err => {
const db = client.db("test");
try {
mongoId = new mongo.ObjectId(req.body.userID);
} catch (err) {
if (err) return res.send({ error: err });
}
const userID = {$eq: {"userID" : (mongoId)}}
const update = {$set: {"name": (req.body.name)}}
db.collection("customers").updateOne(userID, update, function(err, res) {
console.log("POST /quotes");
client.close();
});
});
res.redirect("/user");
});
答案 1 :(得分:0)
我发现了!
app.post("/quotes", (req, res) => {
client.connect(err => {
const db = client.db("test");
const userID = {$eq: {"userID" : (req.body.userID)}}
const update = {$set: {"name": (req.body.name)}}
db.collection("customers").updateOne(userID, update, function(err, res) {
console.log("POST /quotes");
});
});
client.close();
res.redirect("/user");
});
client.close();
必须在函数之外。