【问题标题】:Update fields in object with mongoose in mongodb在 mongodb 中使用 mongoose 更新对象中的字段
【发布时间】:2018-07-17 05:33:04
【问题描述】:

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

我有一个带有一个字段类型对象的用户模型。 我想动态地改变这个对象。但是这段代码不起作用,我用了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();
});

【问题讨论】:

  • 您能更准确地解释一下您想要做什么吗?
  • 你的身份证是什么
  • 这是你完整的猫鼬模式吗?
  • 是的,已经完成了
  • @Aaron 你想存储主题和每个主题的数量链接吗?

标签: javascript mongodb mongoose


【解决方案1】:

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

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

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();

这里是增加每个主题的喜欢的代码:

 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)
    });

这个增量的数据库结果:

希望对你有帮助。

【讨论】:

    猜你喜欢
    • 2015-12-12
    • 2020-05-20
    • 2018-05-08
    • 1970-01-01
    • 2014-07-24
    • 2018-02-21
    • 2017-10-01
    • 1970-01-01
    • 2023-01-18
    相关资源
    最近更新 更多