Mongodb 更新文档时将对象推送到数组属性
我使用mongoose作为模式和持久层 将项添加到现有文档中的数组属性时,它将失败:err将等于Mongodb 更新文档时将对象推送到数组属性,mongodb,mongoose,mongoose-schema,Mongodb,Mongoose,Mongoose Schema,我使用mongoose作为模式和持久层 将项添加到现有文档中的数组属性时,它将失败:err将等于null,raw将等于{n:0,nModified:0,ok:1} 知道为什么会这样吗 更新代码 let concreteAnswer = { questionId: 1, answer: { rating: 34 } }; Participation.update( { _id: 'some-unique-id', 'answers.$.instrumen
null
,raw将等于{n:0,nModified:0,ok:1}
知道为什么会这样吗
更新代码
let concreteAnswer = {
questionId: 1,
answer: {
rating: 34
}
};
Participation.update(
{
_id: 'some-unique-id',
'answers.$.instrumentName': 'some-instrument-name' // instrumentName is unique within the answers array
},
{
$push: {"answers.$.concreteAnswers" : concreteAnswer}
},
(err, raw) => {
console.log(`error occured! raw: ${raw}, error: ${err}`);
}
);
模式定义
var ParticipationSchema = new Schema({
answers: [{
instrumentName: { type: String, enum: validInstruments },
concreteAnswers: [{
questionId: Number,
answer: {}
}]
}]
// further attributes omitted for readability
},
{
timestamps: true
});
var Participation = mongoose.model('Participation', ParticipationSchema);
数据库中的文档
{
"_id": "some-unique-id",
"answers": [
{
"instrumentName": "some-instrument-name",
"_id": "another-unique-id",
"concreteAnswers": []
},
// etc.
}
2017-04-16:根据@VEERAM的评论更改了更新代码:
Participation.update(
{
_id: mongoose.Types.ObjectId('some-unique-id'),
'answers.instrumentName': 'some-instrument-name'
},
{
$push: {"answers.$.concreteAnswers" : concreteAnswerDto}
},
// ERR HANDLING AS ABOVE
}
我还刚刚意识到,现在操作正常(即,文档将在数据库中更新),但它仍将在错误处理中执行
控制台.log
。尝试“answers.instrumentName':“some instrument name”
。从查询中删除$。@Veeram没有任何效果,仍然是相同的问题&错误消息它对我来说很好。您的\u id
是字符串还是objectId?如果objectId尝试\u id:mongoose.Types.objectId(一些唯一的id)
@Veeram,这实际上似乎会有所不同。当发出$
并应用mongoose.Types.ObjectId(“”)时,我得到一个更具体的错误详细信息:MongoError:无法使用部件(instruments of instruments.currentQuestionId)遍历元素({instruments:[{name:“动机驱动因素”,currentQuestionId:0,completed:false,\u id:ObjectId('58f382319d86442fd5840de'),{name:“文化契合度”,currentQuestionId:0,completed:false,{u-id:ObjectId('58f3823119d86442fd5840dd')}}{ok:0,n:0,nModified:0}
你能显示完整的查询吗?你也更新了架构吗?请用最新的更新帖子。请注意,你只能使用位置运算符深入一层。请尝试的“answers.instrumentName”:“some instrument name”
。从查询中删除$。@Veeram没有任何效果,仍然是相同的问题和错误消息e对我来说。你的\u id
是字符串还是objectId?如果objectId尝试\u id:mongoose.Types.objectId(一些唯一的id)
@Veeram,这实际上似乎有区别。当发出$
并应用mongoose.Types.objectId(“”)
时,我得到一个更具体的错误详细信息:MongoError:无法使用该部件(instruments of instruments.currentQuestionId)遍历元素({instruments:[{name:“动机驱动因素”,currentQuestionId:0,completed:false,{id:ObjectId('58f3823119d86442fd5840de')},{name:“文化契合度”,currentQuestionId:0,completed:false,{id:ObjectId('58f3823119d86442fd5840dd')})}){ok:0,n:0,nModified:0}
你能显示完整的查询吗?你也更新了架构吗?请用最新的更新帖子。请注意,你只能用位置运算符深入一层。