我想将单个字符串从我的 mongodb 集合中的文档推入数组。我在 mongoose 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>
Run Code Online (Sandbox Code Playgroud)
有我的应用程序代码:
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('/')
});
Run Code Online (Sandbox Code Playgroud)
有我的收藏模式:
var schemaOptions = {
timestamps: true,
toJSON: {
virtuals: true
},
toObject: {
virtuals: true
}
};
var botyschema = new mongoose.Schema({
_id: String,
name: String,
token: String,
chats: Array
}, schemaOptions);
Run Code Online (Sandbox Code Playgroud)
执行后,我的控制台看起来好像已经推送了一次“czat”对象:
Chats updated for 684206793:AAH5uDpus4Ngw1Z60pj6iOedBGCM8Vq0
Run Code Online (Sandbox Code Playgroud)
但是在我的集合中,两个对象已附加到我的数组中,看起来:
"chats": [
{
"name": "chat_main",
"chatid": "100516120633"
},
{
"name": "chat_main",
"chatid": "100516120633"
}
],
Run Code Online (Sandbox Code Playgroud)
我的架构或查询中缺少某些内容?
| 归档时间: |
|
| 查看次数: |
1392 次 |
| 最近记录: |