node.js - 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"
}
],
我的架构或查询中缺少某些内容?
解决方案
推荐阅读
- python - 当存在 NaN 值时,无法更新 Pandas 数据框中的值
- wordpress - 将产品添加到购物车后,我想留在同一页面上。不想去购物车/结帐或产品页面
- tfs - 如何在 TFS 中获取源期间忽略不包含的特定目录
- encoding - 带一个额外字符的 base64 解码
- python - 暂停 pywinauto 循环并重新开始?
- static-site - 是否有任何支持增量构建的静态站点生成器?
- macos - zsh 的 MacOs 终端问题
- javascript - 在 Heroku 上部署时的文件夹结构
- sqlite - flutter sqlite事务使用错误警告数据库已被锁定
- flutter - XMLHttpRequest 错误。在 Flutter Web 应用程序中调用 api 时