mongodb 如何在mongoose上递增和添加数组

nnsrf1az  于 2023-02-15  发布在  Go
关注(0)|答案(1)|浏览(138)

在我的数据库中,我有一个user表,其中包含2列:scorehistory

我有另一个名为card的表,其中包含一些特定的信息&一张卡片_id
每次单击特定的卡时,我希望调用'/CardClicked'路由器:

  • score列上添加(增量)特定数值(1.5
    ***将购物车_id的值添加到history列的数组中:(要保存,用户单击了哪张卡)

我想在我的数据库里有这样的东西:

users:
{ "_id" : 1, "score" :  6.0, "history" : [ 62k6hf45b0af050fe, 69k5hf45b0af450fg, 65k5hf45b0af450fg, ]}
{ "_id" : 2, "score" :  4.5, "history" : [ 65k5hf45b0af450fg,] }
{ "_id" : 3, "score" : 10.0, "history" : [ 66k5hf45t0af930rp, 67k5hf45b0af450fg, 62k6hf45b0af050fe, 61y5hf884b0af450vb, ] }

但是,idk为什么它不能正确更新列,但是我没有任何错误,我的代码我做了它:
我的用户架构. js:

const mongoose = require('mongoose')

const UserSchema = new mongoose.Schema({
...
score: {
  type: Number,
},
history: {
  type: [String]
 },
 createdAt: {
   type: Date,
   default: Date.now,
  },
})

module.exports = mongoose.model('User', UserSchema)

我的路由器. js:

app.post('/CardClicked', async function (req, res){

  console.log("User ID "+req.user._id, "Card ID : "+req.body._id);

try{       
   const condition = { _id: req.user._id };

   //the req.body._id contain the card id from my front to send that to router
   const putPostID = { $addToSet: { history: req.body._id }};

   const additionalPoints = {$inc : { score : 1.5 }};

   await User.findOneAndUpdate(condition, additionalPoints, putPostID, {upsert: true})

}catch(err){
 res.status(500).send({error: err })
 }
});
0vvn1miw

0vvn1miw1#

每个更新操作必须进入一个对象。在您的情况下:

User.findOneAndUpdate(condition, {
    $inc: { score: 1.5 },
    $addToSet: { history: history: req.body._id },
  }, 
  { upsert: true },
)

相关问题