使用Mongoose从Form Submit上的React组件上进行MongoDB调用会引发错误-TypeError:组不是下面一行的构造函数
let group1 = new Group
我有一个服务器文件,在其中初始化连接。
server.js
const mongoose = require('mongoose');
mongoose.connect('dbName',{ useNewUrlParser: true });
mongoose.connection.once('open',() =>{
console.log('connected to the database');
});
然后有一个名为 group.js
的模型文件const mongoose = require('mongoose');
var groupSchema = new mongoose.Schema({
groupName: String
});
module.exports = mongoose.model('Group',groupSchema);
组件CreateNew
const Group = require('../models/group');
class CreateNew extends Component {
// code here
render()
// code here
<Form onSubmit = {e => {
let group1 = new Group({
groupName: 'My Group'
});
group1.save(function(err,group1){
if (err) return console.log(err);
console.log('mongo success');
});
}}>
当我将所有代码放在server.js文件中的this之类的某个位置时,代码便起作用了,我可以在Mongo中看到数据。
如果我只是将代码从Form的onSubmit内部移到“ Class NewNew extended Component”行之前进行测试,那么它将引发以下错误
编译后无法覆盖
Group
模型。
在此行
module.exports = mongoose.model('Group',groupSchema);
答案 0 :(得分:2)
我将向您简要介绍该项目,其中包括前端和后端。
后退
1.1 server.js
const express = require('express');
const app = express();
const port = process.env.PORT || 80;
const http = require('http').Server(app);
const mongoose = require('mongoose');
const routes = require(path_to_api.js)(router);
app.use('/myApi', routes)
//***Here you should implement more details about your project such as routes, body parsers and other middlewares*****//
mongoose.connect('mongodb://localhost:27017/your-app-name', err => err?console.log(err):console.log('Successfully connected to MongoDB'));
http.listen(port, ()=> console.log(`Server running on ${port}`))
1.2模型,group.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let groupSchema = new Schema({
groupName: {
type: String
}
});
module.exports = mongoose.model('Group',groupSchema);
1.3 api.js(仍然是后端!!!)
const Group = require(path_to_group.js);
module.exports = router => {
router.post('/group', (req, res)=> {
let group = new Group();
group.groupName = req.body.groupName;
//Save in database
group.save(function(err){
...
})
}
return router
}
前锋
2.1 Ajax调用(service.js)
function group(data){
return fetch('/api/authenticate',{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-type': 'application/json'
},
body: JSON.stringify(data)
}).then(response => response.json()).then(data => {
return data //Server response
})
}
export {group}
2.2 React组件
import {group} from //service.js path
class CreateNew extends Component {
constructor(props, context){
this.sendGroupName = this.sendGroupName.bind(this);
}
this.sendGroupName(){
let data = //data received from form after submit
//It is the most important part from the frontend - sending data to the server
group(data).then(res => {
//do somenthing with servers response
}
}
render(){
<Form onSubmit={this.sendGroupName}>
//Form content such as inputs, labels...
<Form/>
}
这是我关于MEAN项目的快速解释。我希望对您有用。