【问题标题】:MongoDB array stays empy after POSTPOST 后 MongoDB 数组保持为空
【发布时间】:2020-07-05 10:57:49
【问题描述】:

如果一个 preform 发布请求(每个失眠),“游戏”数组保持为空。我错过了什么吗?

更新:array.push({}) 之后的新错误

“errorValidationError: games.0.gameID: Path gameID is required., games.0.isGameActivated: Path isGameActivated is required., games.0.isStartTimeTBD: Path isStartTimeTBD is required., 游戏。 0.startDateEastern:路径 startDateEastern 是必需的,games.0.startTimeISO:路径 startTimeISO 是必需的,games.0.hTeam:路径 hTeam 是必需的。games.0.hTeamScore:路径 hTeamScore是必需的。games.0.hTeamTricode: 路径hTeamTricode 是必需的。games.0.vTeam: 路径vTeam 是必需的。games.0.vTeamScore: 路径vTeamScore 是必需的。games.0。 vTeamTricode:路径 vTeamTricode 是必需的。"

【问题讨论】:

  • 看看更新后的答案。

标签: javascript arrays node.js mongodb mongoose


【解决方案1】:

您忘记在 newGame 对象上调用 savenew Game({ ... }) 只会创建您创建的模型的对象。您需要在对象上调用save 方法将其保存回数据库。

newGame.save()

更多信息可以找到here

更新后编辑

我注意到您在构建对象时也提供了 _id 字段。如果您打算更新现有文档,那么我强烈建议您使用 mongoose 提供的findAndUpdate 风格之一。您可以使用几种方法来执行此操作,例如 findByIdAndUpdatefindOneAndUpdate 或简单的 update,将 upsert 的值设置为 true(如果符合条件的文档不存在,那么它将在upsert=true)。

让我知道这是怎么回事。

【讨论】:

  • 哦,我的错,截图没有显示,但我确实调用了 save() 方法
  • 这只是向 MongoDB 添加新游戏。要更新这些收藏,我将使用您提到的方法。谢谢!
【解决方案2】:

您使用属性games 定义您的模型,该属性中包含所有信息。

创建模型时,您没有使用 games 属性。

试试这个:

const newGame = new Game({_id});
newGame.games.push({ // your data here }); 
newGame.save();

【讨论】:

  • 感谢您的回复,但现在我不断收到 valitadionErrors,尽管我提交的 JSON 是正确的。
【解决方案3】:

知道了!

我太傻了...它需要先循环请求,然后将其推送到数组!这是代码:

// ADD GAMES
router.route('/add').post((req, res) => {
    const _id = req.body._id;
    let games = [];
    req.body.games.forEach(game => {

        const gameID = game.gameID;
        const isStartTimeTBD = game.isStartTimeTBD;
        const isGameActivated = game.isGameActivated;
        const startTimeEastern = game.startDateEastern;
        const startDateEastern = game.startDateEastern;
        const startTimeISO = game.startTimeISO;
        const vTeam = game.vTeam;
        const vTeamTricode = game.vTeamTricode;
        const vTeamScore = game.vTeamScore;
        const hTeam = game.hTeam;
        const hTeamTricode = game.hTeamTricode;
        const hTeamScore = game.hTeamScore;

        games.push({
            gameID,
            isGameActivated,
            isStartTimeTBD,
            startDateEastern,
            startTimeEastern,
            startTimeISO,
            hTeam,
            hTeamScore,
            hTeamTricode,
            vTeam,
            vTeamScore,
            vTeamTricode,
        });
    });

    const newGame = new Game ({
        _id,
        games: games
    })

    newGame.save()
    .then(() => res.json('Game added cuz'))
    .catch(err => res.status(400).json('error' + err));

});

【讨论】:

    猜你喜欢
    • 2019-06-13
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    相关资源
    最近更新 更多