How can I update existing mongodb database with a new array in Node js

53 Views Asked by At

My mongodb data is looking like this

[{"_id":"66076517c835e00d55714b41","UMKC":{"users":{"professors":[],"students":[],"admins":[]}}}]
,{"_id":"66076517c835e00d55714b41","UNT":{"users":{"professors":[],"students":[],"admins":[]}}}]]

I want to update the users accroding to their roles. The data needs to be appeneded looks like this

{
'fname':fname,
'lname':lname,
}

I tried updating it like this

router.post('/register', async (req, res) => {
    const { fname, lname, email, univName, id, role, password, _id } = req.body;
    const adminData = { fname, lname, email, id, password }
    const filter = { _id: new ObjectId(_id) }
   
    try {
        const updateResult = await Users.updateOne({filter},
            {$push:{
                'users.admins':{
                    'fname':fname,
                    'lname':lname,
                    'id':id,
                    'email':email,
                    'password':password
                }
            }}
            );console.log(updateResult)
    } catch (error) {
        console.log(error)
    }
})


I followed a thread in mongodb website

The Users model looks like this

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({
    id: {
        type: Number,
        required: true,
        unique: true
    },
    fname: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 50
    },
    lname: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 50
    },

    email: {
        type: String,
        required: true,
        unique: true,
        validate: {
            validator: (email) => /^[\w-\.]+@([\w-]+\.)+[a-zA-Z]{2,4}$/.test(email),
            message: 'Please enter a valid email address.'
        }
    },
    password: {
        type: String,
        required: true,
        minlength: 8
    }
});

const Users = mongoose.model('Users', userSchema);

module.exports = Users; // Export the Users model directly

The data is not being updated in the db. Is there something I am doing wrong?

EDIT:

I tried changing the variable inside the push like this

'users.admins' to 'UNT.users.admins' also `[${univName].users.admins`

just to see if it works. But no luck

0

There are 0 best solutions below