在mongodb中使用猫鼬更新对象中的字段

时间:2018-07-16 15:57:19

标签: javascript mongodb mongoose

我在mongodb中有一个简单的集合。 我用猫鼬。

我让用户模型具有一个字段类型对象。 我想动态更改此对象。但是此代码不起作用,我使用了Cell c = row.getCell(1, Row.RETURN_BLANK_AS_NULL); if (c == null) { // do whatever } findByIdAndUpdate()findByIdfindOne()

findOneAndUpdate()

1 个答案:

答案 0 :(得分:0)

我相信,要解决此问题,您需要在架构中添加更多字段:

我用此数据创建了一个示例:

const UsersSchema = new mongoose.Schema({
  likes :[
    {
      thema:{
        type: String
      },
      likes_amount:{
        type: Number
      },
      _id:false
    }]
});

module.exports = mongoose.model('Users', UsersSchema);

我添加了一个用户:

   var newUser = new UserModel({
      likes:[{
        thema:'foo',
        likes_amount:1
       }]
   });
   newUser.save();

item_saved

以下代码可增加每个主题的点赞次数:

 const thems = ['foo', 'bar'];
  const userId = "5b4d0b1a1ce6ac3153850b6a";

  UserModel.findOne({_id:userId})
    .then((result) => {

      var userThemas = result.likes.map(item => {
        return item.thema;
      });

      for (var i = 0; i < thems.length; i++) {
        //if exists it will increment 1 like
        if (userThemas.includes(thems[i])) {
          UserModel.update({_id: result._id, "likes.thema" : thems[i]}, {$inc: {"likes.$.likes_amount": 1}})
            .then((result) => {
              console.log(result);
            }).catch((err) => {
              console.log(err)
            });
        } else {
         //if doesn't exist it will create a thema with 1 like
          UserModel.update({_id: result._id},
            {
              $addToSet: {
                likes: {
                  $each: [{thema: thems[i], likes_amount: 1}]
                }
              }})
            .then((result) => {
              console.log(result);
            }).catch((err) => {
              console.log(err)
            });
        }
      }
    }).catch((err) => {
     console.log(err)
    });

此增量的数据库结果:

incremented_field

我希望它能为您提供帮助。

相关问题