javascript - 在 mongodb 中用 mongoose 更新对象中的字段

标签 javascript mongodb mongoose

我在 mongodb 中有一个简单的集合。 我使用 Mongoose 。

我有一个具有一个字段类型对象的用户模型。 我想动态地改变这个对象。但是这段代码不起作用,我使用了findByIdAndUpdate()findByIdfindOne()findOneAndUpdate().

const UsersSchema = mongoose.Schema({
        likes: {}
    },
    { collection: 'users' });

const Users = mongoose.model('Users', UsersSchema);
const id ="5b4c540f14f353a4b9875af4";
const thems = ['foo', 'bar'];

Users.findById(id, (err, res) => {

    thems.map(item => {
        if (res.like[item]) {
            res.like[item] = res.like[item] + 1;
        } else {
            res.like[item] = 1;
        }
    });
    res.save();
});

最佳答案

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

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

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

希望对您有所帮助。

关于javascript - 在 mongodb 中用 mongoose 更新对象中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51365832/

相关文章:

node.js - Elasticsearch 返回 IndexMissingException

arrays - 将文档推送到 Mongoose 模型数组中的子文档中

javascript - npx create-react-app <name> 在某个部分后停止运行

javascript - 如何通过分配点后的最后两位数字将字符串转换为 float ?

javascript - 尝试连接 angularJS $http 时出现 mongodb 服务器错误

performance - NodeJs 性能问题

javascript - SAPUI5 分段按钮选择

javascript - 解决 promise 中的 promise 顺序

node.js - Mongoose .find 字符串参数

node.js - 在连接字符串中使用数据库名称时出现 Mongoose 连接错误