node.js - MongoDB - addToSet 不向数组添加元素
问题描述
“猫鼬”:“^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”添加到用户,其 id 由“petition.user”返回。
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”数组中重复值,因此推送不是一种选择。
我究竟做错了什么?
解决方案
首先,欢迎来到 StackOverflow!
我不得不假设你可能有一些东西不能很好地协同工作,因为你说你正在使用 Mongoose,为此我做了一个非常简单的项目,你可以在 GitHub 中查看
我在其中创建了一个非常简单的架构
const UserSchema = mongoose.Schema({
role: [{
type: String
}],
guid: {
type: String,
required: true
},
});
然后使用 Mongoose API创建、更新和查找用户
const guid = uuidv4();
// create user
await UserModel.create({ guid });
log('user created');
["admin", "user", "admin"].forEach(async (role) => {
// add role to user
await UserModel.updateOne({ guid }, { $addToSet: { role } });
log(`user role updated with ${role}`);
});
// read user
const newUser = await UserModel.where({ guid }).findOne();
log(JSON.stringify(newUser, null, 2));
并且输出是预期的
user created
user role updated with admin
user role updated with user
user role updated with admin
{
"role": [
"admin",
"user"
],
"_id": "60a2397b1c488d4968d6ed46",
"guid": "26ccacbf-ddbc-4cbf-ac69-2da3235e156b",
"__v": 0
}
随意查看源代码、克隆、运行和测试,并注意我实际上使用的是 Mongo 命令$addToSet
推荐阅读
- javascript - JS 中异步的一个线性结果?
- android - Android RecyclerView 使用组合行制作固定网格布局
- css - 应用 !important 于
- node.js - node.js / promises / 错误消息:...不是函数
- r - RStudio - 在 str_view_all 的输出中滚动
- java - 将 java 日期反序列化为 Instant
- c - 使用 while(1) 在 main() 中将结构实例声明为静态/本地
- python - Keras`model.fit`期间的运行时错误“AttributeError:'tuple'对象没有属性'_keras_mask'”
- javascript - 在尝试访问对象时添加变量
- react-native - REACT-Native react-navigation-tabs createBottomTabNavigator tabBarVisible false 不起作用