简体   繁体   中英

Update by id with mongoose doesn't find the document

Found the problem while writing this.
As it may help others not searching in the right place like me, you will find the answer below.

I can't seem to make a mongoose Model.update() request work, when a Model.findOne() with the same condition does.

To illustrate, here is my code:
Schema :

var GeolocSchema = new mongoose.Schema({
  id: {
    type: String,
    required: true,
    unique: true
  },
  count: Number
});

An express test route showing the seemingly broken update attempt:

router.get('/test', function(req, res, next) {
  var doc = {
    id: '50_633-20_059',
    count: 3,
    density: 1
  };

  var promise = Geoloc.update({
    id: doc.id
  }, {
    $set: {
      density: doc.density
    }
  }).exec();

  promise.then((result, err) => {
    if (err) return next(err, null);
    res.status(201).json(result);
  });
});

Results in:

{
  "ok": 0,
  "n": 0,
  "nModified": 0
}

An express test route showing the working findOne call:

router.get('/test2', function(req, res, next) {
  var doc = {
    id: '50_633-20_059',
    count: 3,
    density: 1
  };

  var promise = Geoloc.findOne({
    id: doc.id
  }).exec();

  promise.then((result, err) => {
    if (err) return next(err, null);
    console.log('Update result: ', result);
    res.status(200).json(result);
  });
});

Results in:

{
  "_id": "5885d33239f30034de9a38d0",
  "id": "50_633-20_059",
  "count": 3,
  "__v": 0,
}

Credits to this unaccepted answer for putting me on the right track.

The culprit was my schema.
Interestingly enough (for a schema-less database), an update operation can't be made on non-existing fields: probably a fail safe to prevent a DB flood from an external source.
Note that it works as expected via the Mongo CLI.

Which means that the only necessary change in the code above was the following:

Schema :

var GeolocSchema = new mongoose.Schema({
  id: {
    type: String,
    required: true,
    unique: true
  },
  count: Number,
  density: Number // This is mandatory!
});

More infos here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM