简体   繁体   English

如何通过单击前端按钮在 mongoDB 上添加收藏?

[英]How can I add Collection on mongoDB by clicking button on frontend?

I am building a Chat application where I need to add more rooms(groups).我正在构建一个聊天应用程序,我需要在其中添加更多房间(组)。 I have used MongoDB for the database.我已将 MongoDB 用于数据库。

This is my Schema.这是我的架构。

 import mongoose from "mongoose"; const Schema = mongoose.Schema( { message: String, name: String, timestamp: String, received: Boolean, }); const messageContent = mongoose.model('messageContent', Schema); export default messageContent;

I can add Collections easily by going on Mongodb.com but I want to add it by using a button on the frontend.我可以通过 Mongodb.com 轻松添加 Collections 但我想通过使用前端的按钮来添加它。

This is frontend where I have made a button and onClicking it, a prompt comes and we have to write the room name.这是我制作按钮并单击它的前端,出现提示,我们必须写下房间名称。 But after that, my code is giving me an error.但在那之后,我的代码给了我一个错误。

 import { Avatar } from '@material-ui/core'; import React from 'react'; import mongoose from "mongoose"; import "./SidebarChat.css"; import Schema from "./messages"; function SidebarChat({adddNewChat}) { const db = mongoose.connection; const createChat = e => { const roomname = prompt("Add a new chat name"); if(roomname){ console.log("roomName is created: ", roomname); mongoose.model('room', Schema); } } return?adddNewChat: ( <div className="sidebarChat"> <Avatar /> <div className="sidebarChat__right"> <h2>Room Name</h2> <p>Last Message</p> </div> </div> ) : ( <div className="sidebarChat" onClick={createChat}> <h2> Add new Chat</h2> </div> ) } export default SidebarChat

Please tell me how can I do this.请告诉我我该怎么做。

It seems not a good way which put react and mongoose together.将 react 和 mongoose 放在一起似乎不是一个好方法。

It's because "react" expected to be run by browser like firefox, chrome, ...etc.这是因为“react”预计将由 firefox、chrome 等浏览器运行。 And those browser doesn't fully support functions from "mongoose" and vice versa.这些浏览器不完全支持“猫鼬”的功能,反之亦然。

Mongoose's browser library does not support saving documents, queries, populate, discriminators, or any other Mongoose feature other than schemas and validating documents. Mongoose 的浏览器库不支持保存文档、查询、填充、鉴别器或除模式和验证文档之外的任何其他 Mongoose 功能。

Mongoose in browser浏览器中的 Mongoose

On the other hand, "mongoose" would be run by pure "node.js" which doesn't have a DOM structure to render.另一方面,“mongoose”将由纯“node.js”运行,它没有要渲染的 DOM 结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM