猫鼬查询问题-$ push两次推送元素

时间:2018-10-04 04:41:56

标签: node.js mongoose

我想将单个字符串从mongodb集合中的文档推入数组。 我正在将nodejs和mongoose v5.3.1一起使用

我将数据放入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"
            }
          ],

我在架构或查询中缺少什么?

4 个答案:

答案 0 :(得分:1)

我有类似的问题,我通过将$push更改为$addToSet来解决了。

$addToSet documentation

希望会有所帮助。

答案 1 :(得分:0)

https://mongoosejs.com/docs/schematypes.html

尝试将您的架构更改为此

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

var botyschema = new mongoose.Schema({
_id: String,
name: String,
token: String,

chats: [{ 
  "name": String,
  "chatid": Number
 }]

}, schemaOptions);

或者您可以尝试

chats: [{}]

但是我想这会打开它来接收任何输入。

答案 2 :(得分:0)

我不确定addToSet是否是最佳解决方案,因为查询执行了两次。

如果您同时使用了回调和promise,则会使查询执行两次。

因此选择其中之一将使其正常工作。

答案 3 :(得分:0)

我和你有同样的问题,所以我尝试删除“await”,我成功了

相关问题