【发布时间】:2018-06-12 15:23:57
【问题描述】:
我想更新一个 mongodb 集合,但不知道要更新多少字段和哪些字段。例如,如果我有一个用户,他们在不同的页面上更新关于他们的信息,那么更新的字段并不总是相同。
以下是我目前关于如何解决此问题的想法,但我对替代方案持开放态度。
app.post("/user", (req, res) => {
console.log(req.body);
// req.body can consist of 1 or more of the following { FirstName, LastName, Email, Interests, UserRole }
const CreatedAt = Date.now();
if (req.body.Name) {
let promise = User.findOne({ Name: req.body.Name });
promise.then(user => {
for (let key in req.body) {
// Name will print but nothing else, nothing is updated either and there are no errors
console.log(key);
User
.where({_id: user._id })
.setOptions({ multi: true })
.update({ $set: { [key]: key } })
.update({ $set: { UpdatedAt: Date.now() } })
.catch(err => res.json({message:"Failed to update the database."}));
}
}).catch(err => res.json({message:"User could not be found."}));
} else {
res.json({message:"Please provide an email and a password."});
};
});
这里的大问题是我不知道哪个或哪些字段将被更新,并且我不想花很长时间检查以下每个可能的值是否可用。
【问题讨论】:
标签: javascript node.js database mongodb mongoose