Update a field in Mongoose if the new value is not null?

0

having a Schema like this:

const FarmSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  extension: {
    extension: {
      type: Number,
      min: 1,
      max: 1000,
      required: true
    },
    measure: {
      type: String,
      enum: ['Hectareas', 'Manzanas'],
      required: true
    }
  },
  animals: [mongoose.model('Animal').schema],
  outs: {
    type: Array,
    required: true
  },
  outs: {
    type: Array,
    required: true
  },
  plans: {
    type: Array,
    required: true
  }
}, {
  timestamps: true,
  useNestedStrict: true
});

And in the controller to update Farms this:

exports.update = (req, res) => {
  User.update(
    {
      username: req.params.username,
      'farms._id' : req.params.idFarm
    },
    {
      $set: { // fix me 
        'farms.$.name': req.body.name,
        'farms.$.extension': req.body.extension
      }
    }
  )
    .then(farm => {
      res.send(farm);
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while retrieving all farms."
      });
    });
};

What I want is that if the user only wants to modify the 'name' field, we send a JSON like this to the server and only update the name field without changing the 'extension' field:

{
    "name": "Finca 99"
}

The problem is that if I do this, the 'extension' field becomes null or vice versa.

    
asked by alex22596 05.05.2018 в 21:31
source

1 answer

1

You've already tried this:

var myquery = { name: "Tu nombre actual" };
var newvalues = { $set: {name: "Finca 99"} };
dbo.collection("customers").updateOne(myquery, newvalues, function(err, res) {...

Tell me if you tried to do the update in this way or are you doing something else, you can see the complete documentation in link

Any questions, you tell me.

Greetings!

    
answered by 07.05.2018 в 15:44