These are chat archives for Automattic/mongoose

1st
May 2017
William Johnson S. Okano
@williamokano
May 01 2017 06:20
HI
Can someone help me? I'm trying to update an model with findByIdAndUpdate and I'm getting error 11000 saying that I have a duplicated index.
EntityModel.findById(req.params.id)
    .then(doc => Object.assign(doc, value))
    .then(doc => doc.save())
    .then(() => res.status(200).json())
    .catch(err => res.status(500).json(err))
;
With the following schema:
const schema = new mongoose.Schema({
    entity: {
        type: String,
        index: {
            unique: true
        }
    },
    fields: Array
}, {timestamps: true});
Nicholai Nissen
@Nicholaiii
May 01 2017 11:33
I think your errors are due to Object.assign. Use model.findByIdAndUpdate(req.params.id, {$set: value})
@williamokano
also, unless this is your style choice, status(200) is absolutely redundant as its the default status.
Nicholai Nissen
@Nicholaiii
May 01 2017 11:55
@BernardoFBBraga Mongoose has really good API docs. http://mongoosejs.com/docs/api.html#error-js
William Johnson S. Okano
@williamokano
May 01 2017 18:59
@Nicholaiii I'll try this way, and answer you back. I tried with findByIdAndUpdate, but without the $set, and got the same error.
I got the same error with this code
                        EntityModel.findByIdAndUpdate(req.params.id, {$set: value})
                            .then(doc => doc.save())
                            .then(() => res.status(200).json())
                            .catch(err => res.status(500).json(err))
                        ;
With this error from mongoose:
{
  "name": "MongoError",
  "message": "E11000 duplicate key error collection: xy-inc.resource index: entity_1 dup key: { : \"bills\" }",
  "ok": 0,
  "errmsg": "E11000 duplicate key error collection: xy-inc.resource index: entity_1 dup key: { : \"bills\" }",
  "code": 11000,
  "codeName": "DuplicateKey"
}