Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

mongoose findOneAndUpdate with upsert does not create new doc

I'm trying to update user doc if user exist or create new user doc if user does not exist:

app.post('/userUpdate', async (req,res)=> {
    var body = req.body;

    try{
        const updatedUser = await User.findOneAndUpdate(body.facebookId, body, {new: true, upsert: true, runValidators: true});
    res.send({updatedUser});
    } catch (e) {
        res.send(400).send(e);
    }
});

but the result is updating existing user if the query (body.facebookId) does not exist.

Are there mongoose users who can help? Thanks in advance.

Hey Tal. I wish I could help, but I have no experience with Mongo. Hope you get it figured out!