使用mongoose和findOneAndUpdate更新数组抛出错误

时间:2017-07-20 18:26:19

标签: node.js mongodb mongoose-schema

我需要更新文档中的数组,

但是我收到施法错误。

当' $ addToSet'尝试将字符串强制转换为ObjectId。

该字符串是来自我的前端应用程序的正确ObjectId表示。

我在这里缺少什么?

{ MongooseError: Cast to [ObjectId] failed for value "[{"$addToSet":"5915bec7813317eaabd9897d"}]" at path "perguntasAtivas"
    at CastError (C:\nodeapp\cloudapp\node_modules\mongoose\lib\error\cast.js:26:11)
    at SchemaArray.cast (C:\nodeapp\cloudapp\node_modules\mongoose\lib\schema\array.js:182:15)
    at SchemaArray.cast (C:\nodeapp\cloudapp\node_modules\mongoose\lib\schema\array.js:193:15)
    at castUpdateVal (C:\nodeapp\cloudapp\node_modules\mongoose\lib\services\query\castUpdate.js:263:22)
    at walkUpdatePath (C:\nodeapp\cloudapp\node_modules\mongoose\lib\services\query\castUpdate.js:141:22)
    at castUpdate (C:\nodeapp\cloudapp\node_modules\mongoose\lib\services\query\
castUpdate.js:70:18)
    at model.Query._castUpdate (C:\nodeapp\cloudapp\node_modules\mongoose\lib\qu
ery.js:2808:10)
    at castDoc (C:\nodeapp\cloudapp\node_modules\mongoose\lib\query.js:2834:18)
    at model.Query.Query._findAndModify (C:\nodeapp\cloudapp\node_modules\mongoo
se\lib\query.js:2004:17)
    at model.Query.Query._findOneAndUpdate (C:\nodeapp\cloudapp\node_modules\mon
goose\lib\query.js:1858:8)
    at C:\nodeapp\cloudapp\node_modules\kareem\index.js:257:8
    at C:\nodeapp\cloudapp\node_modules\kareem\index.js:23:7
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)
  message: 'Cast to [ObjectId] failed for value "[{"$addToSet":"5915bec7813317eaabd9897d"}]" at path "perguntasAtivas"',
  name: 'CastError',  stringValue: '"[{"$addToSet":"5915bec7813317eaabd9897d"}]"',
  kind: '[ObjectId]',  value: '[{"$addToSet":"5915bec7813317eaabd9897d"}]',
  path: 'perguntasAtivas',  
  reason:   { MongooseError: Cast to ObjectId failed for value "{ '$addToSet': '5915bec7813317eaabd9897d' }" at path "perguntasAtivas"       
  at CastError (C:\nodeapp\cloudapp\node_modules\mongoose\lib\error\cast.js:26:11)    at ObjectId.cast (C:\nodeapp\cloudapp\node_modules\mongoose\lib\schema\objectid.js:147:13)

我的代码:

const mongoose = require('mongoose');
const ObjectId = mongoose.Types.ObjectId;
var modelosSelecionados=[array containing selected itens]

    modelosSelecionados.forEach(function (item){
                  if (item.selected){
                    ModeloAnamnese.findOneAndUpdate({_id: new ObjectId(item.modeloanamnese._id)},{perguntasAtivas:{'$addToSet':new ObjectId(req.params.id)}}, function (err, data){
                        console.log(err);
                        if(err) {
                          return res.status(500).json({'error' : 'error in deleting address'});
                        }
                      });
                  }
                  else ModeloAnamnese.findOneAndUpdate({_id: new ObjectId(item.modeloanamnese._id)},{perguntasAtivas:{'$pull':new ObjectId(req.params.id)}}, function(err, data){
                        console.log(err);
                        if(err) {
                          return res.status(500).json({'error' : 'error in deleting address'});
                        }
                      });
                });

//架构

const mongoose=require('mongoose');
const modelosAnamneseSchema = new mongoose.Schema({
    nome:{type:String, unique:true},
    utilizado_por:[{type:mongoose.Schema.Types.ObjectId, ref:'Profissional'}],
    padrao:{type:Boolean},
    perguntasAtivas:[{type:mongoose.Schema.Types.ObjectId,ref:'Perguntadeanamnese'}],
    created_at:{type:Date,default:Date.now},
    altered_at:{type:Date,default:Date.now}
});

module.exports=mongoose.model('ModeloAnamnese', modelosAnamneseSchema,'modeloanamneses' );

const mongoose=require('mongoose');
const tipoperguntaAnamneseSchema = new mongoose.Schema({
    nome:{type:String, unique:true},
    created_at:{type:Date,default:Date.now},
    altered_at:{type:Date,default:Date.now}
});

module.exports=mongoose.model('TipoPerguntaAnamnese', tipoperguntaAnamneseSchema,'tiposperguntasanamnese' );

1 个答案:

答案 0 :(得分:1)

正确的顺序是:

{ $addToSet : { perguntasAtivas : new ObjectId(req.params.id) } }

记录在案here

{ $addToSet: { <field1>: <value1>, ... } }