【问题标题】:Update some fields in mongodb via mongoose通过 mongoose 更新 mongodb 中的一些字段
【发布时间】:2015-10-05 18:06:03
【问题描述】:

我正在尝试构建一个简单的 restful API,但我不知道如何通过 mongoose 正确更新我的 mongodb 中的某些字段。

这是我的计划:

   Sound = new Schema({
    "title"    : String,
    "url"     : String,
    "time"  : Number,
    "like"  : {
        "count": Number,
        "timestamps": [Number]
   }
}),

  Artist = new Schema({
    "author"            : String,
    "url_to_author_image"   : String,
    "bio"               : String,
    "sounds"             : [Sound]
});

当有人向 /like/sound_id 发送请求时,我需要增加点赞数并将时间戳添加到数组中。到目前为止,我得到了这样的东西:

router.post("/like/:sound_id", function(req, res){
  var time = Date.now();

  Artist.findOneAndUpdate( {"sounds._id":req.params.sound_id},
  { $inc : { "sounds.$.like.count" : 1 } },
  { $push : { "sounds.$.like.timestamps": time } }, function(err,doc){
    if (!err) res.json({message: "wuuuuhuuu"});
  });
});

但是push部分好像错了。

【问题讨论】:

  • 发生了什么让你说它错了?错误?例外?字段未更新?
  • 我收到一条 wuuuuhuuu 消息。点赞数增加,但时间戳字段中没有任何反应。

标签: node.js mongodb express mongoose


【解决方案1】:

您需要将$inc$push 组合成一个对象,否则$push 将被解释为选项参数:

Artist.findOneAndUpdate(
  { "sounds._id": req.params.sound_id },
  { $inc : { "sounds.$.like.count" : 1 },
    $push : { "sounds.$.like.timestamps": time } },
  function(err,doc){
    if (!err) res.json({message: "wuuuuhuuu"});
  });

【讨论】:

    【解决方案2】:

    这是有效的,但我不确定它是否是最有效的解决方案。

    Artist.find({"sounds._id":req.params.sound_id}, function(err, sound){
        sound[0].sounds.id(req.params.sound_id).like.count++;
        sound[0].sounds.id(req.params.sound_id).like.timestamps.push(time);
        sound[0].save(function(err){
          if (!err) res.send(200);
        });
      }); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-01
      • 2011-10-17
      • 2017-06-27
      • 2018-06-05
      • 2017-02-12
      • 2016-12-15
      • 1970-01-01
      相关资源
      最近更新 更多