daman
daman

Reputation: 102

Upserting with Mongoose

I have a schema that is defined like

var UserSchema = mongoose.Schema({
    user: {
        ipAddress: String,
        pollIDs: [{
            id: String
        }]
    }
});

var User = module.exports = mongoose.model('User', UserSchema);

What I want to create is a route that checks the requests ip address, see if it exists in the database, if it doesn't create a new document with the ipAddress property set accordingly and the current req.body.poll_id to be an element in the pollIDs array.

However, if there is a document with that ip address I want the req.body.poll_id to be pushed into the pollIDs array.

I would demonstrate my first attempt, but I know that I've messed up the parameters on the findOneAndUpdate call.

Upvotes: 1

Views: 55

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311835

Should be as simple as:

User.findOneAndUpdate(
    {'user.ipAddress': req.body.ipAddress},
    {$push: {'user.pollIDs': {id: req.body.poll_id}}},
    {upsert: true, new: true},
    (err, doc) => {...});

The upsert will take the query object and apply the update operation to it in the case where it needs to insert a new document.

Upvotes: 1

Related Questions