我是Node.js的新手,我知道这是一个非常常见的问题,很多人都问过同样的问题。但是您知道在我的情况下没有任何解决方案有效。
请看一下代码,让我知道是否错过了一些事情
谢谢!
这是与Mongo db交互的node.js应用程序。
Product.controllers.js
const Products = require("../models/Product.models");
exports.Product_create = function(req, res, next){
console.log(req.body.Name); //For test only - Here I am getting the values
console.log(req.body.Age); //For test only - Here I am getting the values
let newProduct = new Products()
{
first_name = req.body.Name,
age = req.body.Age
};
newProduct.save(function (err) {
if (err) {
return next(err);
}
res.send('Product Created successfully')
})
};
exports.test = function(req, res){
console.log("test controller reached successfully!");
};
Product.models.js
var mongoose = require("mongoose");
var schema = mongoose.Schema;
let ProductSchema = new schema({
first_name : {type: String, required: true, max: 100},
age: {type:Number, required: true}
});
//export model
module.exports = mongoose.model("Product", ProductSchema);
这是我发送的请求。
我在console.log(req.body.Name);
和console.log(req.body.Age);
中收到正确的输出。但是它仍然不能保存数据。
答案 0 :(得分:1)
错误在于您的产品初始化
const Products = require("../models/Product.models");
exports.Product_create = function(req, res, next){
console.log(req.body.Name); //For test only - Here I am getting the values
console.log(req.body.Age); //For test only - Here I am getting the values
let newProduct = new Products(
{
first_name:req.body.Name,
age:req.body.Age
});
newProduct.save(function (err) {
if (err) {
return next(err);
}
res.send('Product Created successfully')
})
};
exports.test = function(req, res){
console.log("test controller reached successfully!");
};
您需要提供first_name and age
作为键值对