[英]Mongoose update multiple fields in one document in nodejs
I've a collection of ranks in ship.我在船上有一系列等级。 It has rank and type .
它有rank和type 。
Some of the ranks and their corresponding types are:一些等级及其对应的类型是:
and some other officer types.和其他一些军官类型。 User can edit both rank and types(If there's typo or the rank is in wrong type).
用户可以编辑排名和类型(如果有错字或排名类型错误)。 But I just find the correct mongoose way to do so.
但我只是找到了正确的 mongoose 方法。 This is what I've tried
这是我尝试过的
const editOneRank = async (req, res) => {
const rank = req.body.rank;
const rankData = await Rank.findOne({rank});
console.log(rankData);
if(!rankData){
res.status(200).send({
message: "rank not found",
})
}else{
const editedRankFromBody = new Rank({
rank: req.body.rank,
type: req.body.type
});
try{
await Rank.findOneAndUpdate(rankData._id, {"rank": req.body.rank,"type": req.body.type}, (err, result)=>{
if(err){
res.status(400).send({
data: "couldn't update rank"
})
}else{
console.log(result);
res.status(200).send({
data: "Rank Updated"
})
}
})
}catch(err){
res.status(400).send({
data: err+ "hello"
})
}
}
}
But it doesn't update anything I also tried:但它并没有更新我也尝试过的任何东西:
await Rank.findOneAndUpdate(rankData._id, {"type": req.body.type}, (err, result)=>{})
with no luck.没有运气。 What am I doing wrong?
我究竟做错了什么? How do I update both rank and type if somehow the user needs to update both?
如果用户需要以某种方式同时更新排名和类型,我该如何更新?
please try to update using the following:请尝试使用以下内容进行更新:
await Rank.findOneAndUpdate({"_id":rankData._id},
{
"$set":{
"rank": req.body.rank,"type": req.body.type
}
},
(err, result)=>{})
I think you've missed the field name to check for and update its data.我认为您错过了检查和更新其数据的字段名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.