Riyas TK
Riyas TK

Reputation: 1251

mongoose update with push operations on array and set operation on object

I have this mongoose schema

var ContactSchema = module.exports = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  phone: {
    type: Number,
    required: true,
  },
  messages: [
  {
    title: {type: String, required: true},
    msg: {type: String, required: true}
  }],
  address:{ city:String,
            state:String
  }
});

I have initially the collection set with name and phone field. I need to update the collection with new messages into messages array and new address into address object. the function must also need to handle any single operation, ie in some case i have only update to messages array or updates to both name and address. so how i can i do all operations in a single function.

        var messages= {
            title: req.body.title,
            msg: req.body.msg
        }
        Model.findOneAndUpdate({'_id': req.body.id,},{$push: {messages:message}},{upsert: true}, function (err, data) {
            if (err) {
                return res.status(500).send(err);
            }
            if (!data) {
                return res.status(404).end();
            }
            return res.status(200).send(data);
        });

Upvotes: 14

Views: 16350

Answers (1)

chridam
chridam

Reputation: 103355

You could try use both the $set and $push operators in your update object. Suppose, for example, you want to update both name and address fields in one single operation, use the $set on the name field and a $push operation to the address array:

var messages= {
    title: req.body.title,
    msg: req.body.msg
},
query = {'_id': req.body.id},
update = {
    $set: {name: req.body.name},
    $push: {messages: message}
},
options = {upsert: true};

Model.findOneAndUpdate(query, update, options, function (err, data) {
    if (err) {
        return res.status(500).send(err);
    }
    if (!data) {
        return res.status(404).end();
    }
    return res.status(200).send(data);
});

Upvotes: 33

Related Questions