1
我試圖用$inc
增加字段值,但沒有太多成功。我有以下模式:
var postSchema = mongoose.Schema({
title : { type: String, required: true },
body : { type: String, default: '' },
counter : counterSchema
});
var counterSchema = mongoose.Schema({
upvotes : { type: Number, default: 0, min: 0 },
downvotes : { type: Number, default: 0, min: 0 },
view : { type: Number, default: 0, min: 0 }
});
我想在counter
遞增值,和我有什麼是:
...
let where = `{ '_id': ObjectId("${req.body.pid}") }`:
let update = req.body.action === 'up' ? "{ '$inc': { 'counter.upvotes': 1 } }"
: "{ '$inc': { 'counter.downvotes': 1 } }";
Post.findOneAndUpdate(where, update, {'new': true}, (err, post) => {
if (err) return next(err);
console.log('post=' + JSON.stringify(post));
...
我能夠使用本聲明的mongod成功地增加,
db.posts.update({_id: ObjectId('56cd78fddfe1372131a04b4d')}, {$inc: {'counter.upvotes': 1}})
所以我最初認爲它與Mongoose語法有關,並嘗試了多種變體,包括:
- 使用
collection...update().exec(...
)格式 - 圍護鍵和值在單人,雙人,市場中沒有報價
- 省略
ObjectId
,即{ '_id': id) }
但到目前爲止沒有運氣。任何幫助將不勝感激。
PS。該代碼確實成功執行,沒有錯誤,因爲我將選項設置爲{'new': true}
,所以我找回了一篇文章。這只是一個post.counter。[upvote | downvote]在返回的內容或mongodb中增加。
謝謝@JohnnyHK! –