0

I have this schema with

const userSchema = new mongoose.Schema(
{
    skills: [{ name: { type: String, unique: true }, level: { type: Number } }],

and I am trying, after getting an array of objects from the client, to add all of them at once under a user in MongoDB

my old implementation when it was only an array is this one below. I have no idea how to go about it now tho. Could anyone help me?

const { email } = session;
const { skill } = req.body;
if (req.method === 'POST') {
    try {
        const user = await User.findOne({ email });

        const updatedUser = await User.findOneAndUpdate(
            { email },
            { skills: [...user.skills, { name: skill }] }
        );

1 Answer 1

1
const { email } = session;
// object from the client
const { skills } = req.body;
if (req.method === 'POST') {
    try {

        const updatedUser = await User.findOneAndUpdate(
            { email },
            { $set: {skills} }
        );

the best is getting the array correctly formatted from front-end, if not use a map before call findOneAndUpdate

Sign up to request clarification or add additional context in comments.

2 Comments

So I tried till now and I couldn't manage to spread the existing array, and add the new elements to it with $set, but I found $addToSet fixed that for me, So I basically did const { skill: skills } = req.body; if (req.method === 'POST') { try { const user = await User.findOne({ email }); const updatedUser = await User.findOneAndUpdate( { email }, { $addToSet: { skills } } ); Your answer tho put me on the right track, and probably there is a way to do it with $set that I couldn't manage to find. Thank you
nice to hear it man!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.