Home > Enterprise >  How can I insert an user auto-incremented ID in a request response? (MongoDB triggers)
How can I insert an user auto-incremented ID in a request response? (MongoDB triggers)

Time:01-19

I'm working on a sign-up and sign-in system and I was trying MongoDB auto incrementing ids with triggers.

The problem is that when registering I'm sending informations like accessToken, etc. and userId is not included in these informations. Since the trigger will be fired only after creating the user in a collection the automatic created userId won't be sent in the response.

What I need to do or change to insert the user id there? Should I fetch the user id manually and insert in the response? I don't know if it's the best way because it costs time and fetches to the DB. Any suggestion/help is appreciates, thanks and have a good day.

Register request code:

//REGISTER
router.post("/register", async (req, res) => {
    const newUser = new User({
        email: req.body.email,
        password: CryptoJS.AES.encrypt(
            req.body.password,
            process.env.PASS_SEC
        ).toString(),
    });

    try {
        const user = await newUser.save();

        const accessToken = jwt.sign(
            {
                id: user._id,
                isAdmin: user.isAdmin,
            },
            process.env.JWT_SEC,
            {expiresIn:"7d"}
        );

        const { password, ...others } = user._doc;
        res.status(201).json({...others, accessToken});
        return
    } catch (err) {
        console.log(err)
        res.status(500).json(err);
        return
    }
});

My trigger code:

exports = async function(changeEvent) {
    var docId = changeEvent.fullDocument._id;
    
    const countercollection = context.services.get("Cluster0").db(changeEvent.ns.db).collection("counters");
    const usercollection = context.services.get("Cluster0").db(changeEvent.ns.db).collection(changeEvent.ns.coll);
    
    var counter = await countercollection.findOneAndUpdate({_id: changeEvent.ns },{ $inc: { seq_value: 1 }}, { returnNewDocument: true, upsert : true});
    var updateRes = await usercollection.updateOne({_id : docId},{ $set : {userId : counter.seq_value}});
    
    console.log(`Updated ${JSON.stringify(changeEvent.ns)} with counter ${counter.seq_value} result : ${JSON.stringify(updateRes)}`);
    };

About triggers: https://www.mongodb.com/basics/mongodb-auto-increment

CodePudding user response:

I solved it creating my own auto-incrementing userId system, nothing complicated, just didn't used triggers and created the id directly into the register request, don't know if this is the best way to do this.

I created a counters collection, then just created a new document to store a userId counter.

The code is like this:


import Counter from "../models/counter/index.js";

async function getNextSequence(name) {
    let ret =  await Counter.findOneAndUpdate(
           { counterFor: name },
           { $inc: { seq: 1 } },
           {new: true}
    );
    return ret.seq;
 }


//REGISTER
router.post("/register", async (req, res) => {
    const newUser = new User({
        email: req.body.email,
        password: CryptoJS.AES.encrypt(
            req.body.password,
            process.env.PASS_SEC
        ).toString(),
        userId: await getNextSequence('userId')
    });

    try {
        await newUser.save( async (err, user) => {
            if (err) {
                console.log(err);
                res.status(500).json(err);
                return;
            }

            const accessToken = jwt.sign({ id: user._id, isAdmin: user.isAdmin }, process.env.JWT_SEC, { expiresIn: "7d" });
            const { password, ...others } = user._doc;
            res.status(201).json({ ...others, accessToken });
            return;
        });;
    } catch (err) {
        console.log(err)
        res.status(500).json(err);
        return
    }
});
  • Related