U
U
Urbansamurai2017-05-08 18:27:15
MongoDB
Urbansamurai, 2017-05-08 18:27:15

How to change values ​​in an array embedded in a document in MongoDB without changing its _id?

At the moment I found only such a solution. And how to achieve that _id was saved by itself and did not figure it out.
Another question: is it possible to update only those values ​​that are passed to req.body. For example: we transfer only a new name, without a photo. For some reason, in this case, the photo field disappears.

app.put('/models', (req, res) => {

    var d = Devices.update(
        { 'models._id': req.body.modelID },
        { $set: { 'models.$._id': req.body.modelID, 'models.$.name': req.body.name, 'models.$.photo': req.body.photo } },
        (err, result) => {
          if (err) {
            res.send(err)
          } else {
            res.send(result)
          }
        })
  })

The schema looks like this:
var DevicesSchema = new mongoose.Schema({
  name: {
    type: String,
    trim: true,
    unique: true
  },
  photo: {
    type: String,
    trim: true,
    unique: true
  },
  models: [ {
      name: {
        type: String,
        trim: true,
        unique: true
        },
      photo: {
        type: String,
        trim: true
        },
      services: [ {
          name: String,
          price: Number,
          duration: Number,
          guarantee: Number
        }
      ]
    }
  ]
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
emp1re, 2017-05-08
@emp1re

Why is this var d = ? Everything is updated through $set, _id does not change
'models.$._id': req.body.modelID - just remove it.
res.send(err) is very bad practice

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question