首页 > 解决方案 > Mongoose 查询问题 - $push 两次推送元素

问题描述

我想将单个字符串从我的 mongodb 集合中的文档推送到数组中。我正在使用带有猫鼬 v5.3.1 的 nodejs

我将数据放入我的 html 表单中,然后将其提交到服务器。

有我的HTML:

<form action="/addchat" method="post">
            <input type="text" class="form-control" name="chatid" id="addchatid">
            <input type="text" class="form-control" name="chatname">
            <select class="form-control form-control-sm" name="chatbot" id="chatbot">
            <option value="684206793:AAH5uDpus4Ngw1Z60pj6iOedBGCM8Vq0">botname1</option></select><br>
            <button type="submit" class="btn btn-primary">Add</button>
</form>

有我的应用程序代码:

app.post('/addchat', async (req, res) => {

    var czat = {
      name: req.body.chatname,
      chatid: req.body.chatid
    }

    await botsmodel.updateOne({
        token: req.body.chatbot
      }, {
        $push: {
          chats: czat
        }
      },
      async (err, result) => {
        if (err) {
          console.log(`Error updating chats ${err}`)
        } else {
          console.log(`Chats updated for ${req.body.chatbot}`);
        }

      });


    await res.redirect('/')


});

有我的集合模式:

var schemaOptions = {
  timestamps: true,
  toJSON: {
    virtuals: true
  },
  toObject: {
    virtuals: true
  }
};

var botyschema = new mongoose.Schema({
  _id: String,
  name: String,
  token: String,
  chats: Array
}, schemaOptions);

执行后,我的控制台看起来像是推送了一次“czat”对象:

Chats updated for 684206793:AAH5uDpus4Ngw1Z60pj6iOedBGCM8Vq0

但是在我的集合中,两个对象已附加到我的数组中,看起来:

 "chats": [
            {
                "name": "chat_main",
                "chatid": "100516120633"
            },
            {
                "name": "chat_main",
                "chatid": "100516120633"
            }
          ],

我的架构或查询中缺少某些内容?

标签: node.jsmongoose

解决方案


我有类似的问题,我通过更改$push$addToSet.

$addToSet 文档

希望它会有所帮助。


推荐阅读