首页 > 解决方案 > 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”数组中重复值,因此推送不是一种选择。

我究竟做错了什么?

标签: node.jsmongodbmongoosemongoose-schema

解决方案


首先,欢迎来到 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


推荐阅读