猫鼬findByIdAndUpdate尝试更新时失败

时间:2020-10-31 13:43:56

标签: javascript node.js mongoose mongoose-schema

我正在尝试使用新的数组数据更新对象。我收到消息:

“ MongooseError [CastError]:在以下位置将值”“强制转换为ObjectId 路径“ playlistContent”“

我收到“未定义”。

当我console.log我的阵列数据时,一切都很好,但是我无法更新我的文档,也无法弄清楚为什么。

这是我的代码:

FileOutputStream foStream = new FileOutputStream("/tmp/testfile.txt");
FileChannel channel = fileOutputStream.getChannel();
FileLock lock = channel.lock();

有人可以帮助我,如何以正确的方式传递数据,然后更新我的播放列表对象吗?

//我的模式:

router.post("/addspot/:id", async (req, res) => {
  
  // Constants 
  let specficPlaylist = await Playlist.findById(req.params.id);
  let spotFrequency = req.body.spotFrequency;
  let spotAllocate = req.body.spotAllocate;
  let populatedPlaylists = [];
  await specficPlaylist.populate("playlistContent").execPopulate();
  
  // For loop for passing in data in the right order
  for (let i = 0; i < specficPlaylist.playlistContent.length; i++) {
    if (i % spotFrequency == 0) {
      populatedPlaylists =
        populatedPlaylists + spotAllocate + ",";
    }
    populatedPlaylists =
      populatedPlaylists +
      specficPlaylist.playlistContent[i]._id+ ",";
  }
  
  // Array of data which I want to update my Object with
  const playlistData = populatedPlaylists.split(",");
  
  // Trying to update my specific document with the above data, but it fails

  await Playlist.findOneAndUpdate(
    { _id: specficPlaylist._id},
    { playlistContent: playlistData },
    { new: true},
    (err, docs) => {
    }
  );
   res.redirect('back');
});

0 个答案:

没有答案