【问题标题】:Is it possible to update a mongodb collection (using Mongoose) in a post method?是否可以在 post 方法中更新 mongodb 集合(使用 Mongoose)?
【发布时间】:2018-12-30 21:17:35
【问题描述】:

我需要做两件事:

1) 创建 50 多个集合并用文档填充它们

2) 根据我添加的每个文档中的信息,编辑现有集合。

主要用途首先是第一步,它工作正常。因为我正在向数据库添加集合,所以我使用了 post 方法。现在我需要更新另一个集合,在这种情况下,put 甚至是 patch http 方法会更适合。

解决这个问题的正确方法是什么?目前我正在使用 model.findOne 和 mode.Update 但没有任何更新。我想知道是不是因为它是一个 post 方法而不是 put 方法

代码: 添加有效的令牌后,我调用该函数

                      // This adding works fine
                      new tokenModel(tokenSchema).save();
                      // This function is handling the update in a different collection
                      addTraitsToGame(tokenData);

而功能是:

const addTraitsToGame = (tokenData) => {
// Game is another collection I want to update
Game.findOne({ "opensea.game.address": tokenData.asset_contract.address })
  .then(existingGame => {
    if (existingGame) {
      newArrayToReplaceExistingOne= [];
      try {
        // Not really relevant, this is how I fill a new object that will be pushed to the new array
        for (let i = 0; i < someLength; i++) {
          let tokenTrait = tokenData.traits[i];
          let gameTrait = existingGame.opensea.traits.find(trait => trait.type === tokenTrait.trait_type);
          if (gameTrait && gameTrait.form === "values") {
            gameTrait.attributes[tokenTrait['trait_type']] = tokenTrait['trait_count']
            // This is the relevant line, filling up the array with objects
            newArrayToReplaceExistingOne.push(gameTrait);
          }
        }
        // Updating here!
        Game.update(
          { "opensea.game.address": tokenData.asset_contract.address },
          {
            $set: {
              "opensea.game.traits": traitsWithCount
            }
          },
          function (err, user) {
            if (err) return handleError(err);
            else {
              console.log("Update should have been successful");
            }
          }
        );
      }
      catch (err) {
        console.log(err);
      }
    }
  });

}

之后没有任何更新。

【问题讨论】:

  • 请发布猫鼬更新代码
  • Http PUT 或 POST 不会改变猫鼬的行为。您的 model.update 或 model.findOne 可能存在问题。请输入一些有问题的代码以识别问题。
  • 用相关代码编辑

标签: node.js mongodb mongoose


【解决方案1】:

你也可以使用

model.findOneAndUpdate({_id:req.body.id},{key you need to update:"updated value"},(req,res)=>{
 your code here.
}

希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    相关资源
    最近更新 更多