2016-02-26 90 views
0

我有以下架構,並嘗試更新answers.counter中的值。貓鼬位置數組更新

var postSchema = mongoose.Schema({ 
    question  : { type: String, required: true }, 
    answers  : [answerSchema]  
}); 
var answerSchema = mongoose.Schema({ 
    answe   : String, 
    counter  : { type: counterSchema, ref: 'Counter' } 
}); 
var counterSchema = mongoose.Schema({ 
    upvotes  : { type: Number, default: 0, min: 0 }, 
    downvotes  : { type: Number, default: 0, min: 0 } 
}); 

和代碼:

Post.findOneAndUpdate(where, { '$inc': { 'answers.$.counter.upvotes': 1 } }, {'new': true, runValidators: true }, (err, post) => { 
    if (err) return next(err); 
    console.log('post=' + JSON.stringify(post)); 

所以對於where,我曾嘗試以下,其它變型中:

1){ 'answers._id': ObjectId(${req.body.aid}) }

2){ '_id': ObjectId(${req.body.pid}), 'answers._id': ObjectId(${req.body.aid}) }

3){ '_id': ObjectId(${req.body.pid}), 'answers._id': ObjectId(${req.body.aid}) 'answers.counter._id': ObjectId(${req.body.cid}) }

我收到以下錯誤:

MongoError: exception: The positional operator did not find the match needed from the query. Unexpanded update: answers.$.counter.upvotes

這真是莫名其妙我,因爲通過蒙戈控制檯,db.posts.update({'answers._id': ObjectId('56ce1376ab820a5b3a149494')}, {$inc: {'answers.$.counter.upvotes': 1}})

不正確地增加正確的價值,開始我這個整個路徑上。

在此先感謝任何指針。

回答

0

原來我有一個字符串,而不是一個對象where。因此,#1對象的形式解決這個問題:

let where = { '_id': req.body.aid } 

而在以前這是一個字符串形式(使用$ {}模板):

let where = `{ 'answers._id': ${req.body.aid} }`