【问题标题】:MongoDB doesn't push/increment fieldsMongoDB 不推送/增加字段
【发布时间】:2021-06-02 12:31:28
【问题描述】:

我想用 MongoDB 增加一个数字并在数组中推送一个元素,但我的代码不起作用。
这是我的代码:

        let users = mongoose.db("wumpusCave").collection("users")

        let user = await users.findOne({"token": data.user})
        let bot = mongoose.db("wumpusCave").collection("bots").findOne({"id":data.bot})

        if(user != null) {
            if(user.likedBots != null) {
                user.updateOne({$push: {"likedBots": data.id}})
                console.log("bot a cui hai lasciato like aggiunto!!")
            }
            if(bot != null) {
                bot.updateOne({$inc: {"like": 1}})
                console.log("like aggiunto!")
            }
        }

错误:

                user.updateOne({$push: {"likedBots": data.id}})
                     ^

TypeError: user.updateOne is not a function

我该怎么办?
感谢您的建议,抱歉英语不好!

编辑:
使用此代码修复:

        console.log(data)
        let users = mongoose.db("wumpusCave").collection("users")

        let user = await users.findOne({"token": data.user})
        let bots = mongoose.db("wumpusCave").collection("bots")
        let bot = await bots.findOne({"id":data.bot})

        if(user != null) {
            if(user.likedBots != null && bot != null) {
                users.findOneAndUpdate({"token": data.user}, {$push: {"likedBots": data.id}})
                console.log("bot a cui hai lasciato like aggiunto!!")
                bots.findOneAndUpdate({"id":data.bot}, {$inc: {"like": 1}})
                console.log("like aggiunto!")
            }
        }
    })

【问题讨论】:

  • insertOne 插入一个新文档。使用updateOne 更新现有文档。
  • @WernfriedDomscheit 不起作用。说这不是一个函数:user.updateOne({$push: {"likedBots": data.id}}) ^ TypeError: user.updateOne is not a function
  • @WernfriedDomscheit 我已添加完整代码
  • 如果您从答案中得到了解决方案,那么接受答案而不是默默地复制/粘贴解决方案是一个好习惯。

标签: javascript node.js arrays mongodb push


【解决方案1】:
if(user != null && user.likedBots != null && bot != null) {
    users.findOneAndUpdate({"token": data.user}, {$push: {"likedBots": data.id}})
    console.log("bot a cui hai lasciato like aggiunto!!")
    bots.findOneAndUpdate({"id":data.bot}, {$inc: {"like": 1}})
    console.log("like aggiunto!")          
}

【讨论】:

    猜你喜欢
    • 2021-07-03
    • 2012-05-05
    • 2021-08-21
    • 2016-06-20
    • 1970-01-01
    • 2015-02-26
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    相关资源
    最近更新 更多