我有以下架構,並嘗試更新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}})
不正確地增加正確的價值,開始我這個整個路徑上。
在此先感謝任何指針。