node.js - React / Node js和mongodb,发送数据,创建集合但未发送模式数据?
问题描述
所以我有一个 React 应用程序,它有一个表单,假设将输入的数据发送到一些文本区域框中,发送到节点 js 后端,然后发送到 mongodb 实例。大部分工作,React 数据发送到节点服务器,节点服务器在 mongodb 中创建集合,但是 Schema 数据似乎没有被收集。我来自 React 应用程序的控制台日志显示以下内容,
{companyName: "linfox", curtainCodes: "#00000", sinageCodes: "#FFFFF",
Notes: "test", Method: "typed stuff in"}
Method: "typed stuff in"Notes:
"test"companyName: "linfox"curtainCodes: "#00000"sinageCodes:
"#FFFFF"__proto__: Object
UserInput.js:36 Server added successfully
所以 React 应用程序现在正在运行 Node js 代码。(重要的是要注意我正在使用MLAB for mongodb)
服务器.js
//This code requires mongoose node module
const express = require("express");
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors')
const tfiPaintCodesRouter = require('./routes/tfiPaintCodesRouter');
const mongoose = require('mongoose');
const MONGO_URL = 'mongodb://link-to-mlab-instance';
mongoose.connect(MONGO_URL).then(
() => {console.log('Database is connected') },
err => { console.log('Can not connect to the database' +err)
});
const port = process.env.PORT || 3001;
app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/saveInfo', tfiPaintCodesRouter);
app.listen(port, () => {
console.log("Server listening on port " + port);
});
mongoDB Schema 代码
// server/models/Article.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
// Create schema
const PaintInfoSchema = new Schema({
companyName: {
type: String
},
curtainCodes: {
type: String
},
sinageCodes: {
type: String
},
Notes: {
type: String
},
Method: {
type: String
},
},{
collection: 'tfiPaintCodes'
});
module.exports = mongoose.model('PaintInfoSchema', PaintInfoSchema)
tfiPaintCodesRouter.js
// tfiPaintCodesRouter.js
const express = require('express');
const app = express();
const tfiPaintCodesRouter = express.Router();
const PaintInfoSchema = require('../models/PaintInfoSchema.js');
tfiPaintCodesRouter.route('/add').post(function (req, res) {
const tfipaintcode = new PaintInfoSchema(req.body);
tfipaintcode.save()
.then(tfipaintcode => {
res.json('Server added successfully');
})
.catch(err => {
res.status(400).send("unable to save to database");
});
});
tfiPaintCodesRouter.route('/').get(function (req, res) {
PaintInfoSchema.find(function (err, tfipaintcodes){
if(err){
console.log(err);
}
else {
res.json(tfipaintcodes);
}
});
});
module.exports = tfiPaintCodesRouter;
发送数据后,我去 Mlab 可以看到集合已创建,如图所示
但是在集合中,我的数据响应如下。
{
"_id": {
"$oid": "5b7cbe075e4b2c20b02a789b"
},
"__v": 0
}
我不确定我错过了什么!任何帮助表示赞赏。
解决方案
推荐阅读
- r - 如何在 R 的 for 循环中保存更改名称的数据帧?
- django - Django H14 Heroku 错误,我该如何解决?
- javascript - 如何最好地在烧瓶应用程序中动态填充下拉列表?
- json - 修改 json 对象数组
- powershell - 使用employeeid更新员工经理
- python - 在烧瓶中创建可下载文件的问题
- swiftui - 防止 SwiftUI App 进入睡眠操作 WatchOS
- javascript - 谷歌注册不适用于第一次点击元素,但之后工作正常。为什么?
- apache-spark - 为什么一旦我将“mapValues()”应用于 RDD,属性就会消失?
- sql - SQL中多个表中的项目总和