【发布时间】:2021-05-17 17:59:44
【问题描述】:
“猫鼬”:“^5.12.2”
我有一个名为 User 的模式。此模式有一个名为“rol”的字段,类型为 string[],用于多角色应用程序(用户、管理员、Freetour、BarOwner 等)。
向用户添加角色的函数定义如下:
public addRolToUser = (idUser:string, newRol:string):Promise<IUser> => {
try{
return new Promise<IUser>((resolve, reject) => {
User.findByIdAndUpdate(idUser, { addToSet: {rol:newRol} }, {new:true}).then(user => {
return resolve(user);
}).catch(err => {
return reject(err);
});
});
}catch (e) {
throw e;
}
};
但是,这不会更新用户的“角色”字段。以下函数应将角色“FreeTour”添加到具有“petition.user”返回的 id 的用户。
public acceptPetition = async(req:Request, res:Response) => {
try{
return this.solFreeTourService.acceptPetition(req.body.idPetition).then(petition => {
let acceptPromise = new Promise((resolve, reject) => {
// Here I´m invoking the addRolToUser function
return this.userService.addRolToUser(petition.user, "FREETOUR").then((resUser)=>{
// resUser here has the same value for the "rol" field, didn´t get updated.
return resolve(petition);
}).catch(err=>{
return reject(err);
})
})
return acceptPromise.then(petition=>{
return res.status(200).json({petition});
}).catch(e=>{
res.status(400).json({ status: 400, message: "There has been an error." });
});
})
}catch (e) {
res.status(400).json({ status: 400, message: "There has been an error." });
}
}
我不想在“rol”数组中重复值,因此推送不是一个选项。
我做错了什么?
【问题讨论】:
-
这能回答你的问题吗? Push items into mongo array via mongoose
-
那篇文章中的解决方案都不起作用。我什至添加了一个回调函数,它没有导致错误并返回未更改的文档。然后我检查了 MongoDB Compass 上的架构,发现文档没有更新。
-
在向数组添加元素时,您不应该使用
User.findByIdAndUpdate(idUser, { $push: {rol:newRol} }, {new:true})吗?... ????另外,我前段时间在User.updateOne()的 prol 中停止使用User.findByIdAndUpdate推荐... -
@balexandre 请注意,我不希望数组中有重复的值,因此单独推送不是解决方案:我只会推送一个不在数组中的值(这基本上是“addToSet”应该在这里做)。我将用 updateOne 替换 findByIdAndUpdate 并试试我的运气。会找你的
标签: node.js mongodb mongoose mongoose-schema