我正在制作适合个人用户使用的待办事项应用程序。我可以在没有用户ID的情况下将数据粘贴到数据库中,但是当我尝试将google ID添加到架构和数据库时,将引发类型错误。我的猫鼬模式似乎坏了
TodoController.js
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
const keys = require("../configs/keys");
const Todo = require("../models/todo-model")
//Connect to the database
mongoose.connect(keys.mongodb.tododbURL,() => {
console.log("connected to mongodb server");
});
//var data = [{item:"get milk"}, {item:"walk nan"}, {item:"code for a bit"}];
var urlencodedParser = bodyParser.urlencoded({ extended: true });
const authCheck = (req, res, next) =>{
if(!req.user){
//executed if user isn't logged in
res.redirect("/");
} else {
//if logged in
next(); // fires to the next functionS
}
};
module.exports = function(app){
app.get("/todo", authCheck, function(req, res){
//Get data from mongoDB andd pass through view
Todo.find({}, function(err, data){
if (err) throw err;
res.render("todo", {todos:data});
});
console.log(req.user.googleID)
});
app.post("/todo", urlencodedParser,function(req, res){
//get data from view and put it in the database
var newTodo = Todo({item: req.body, googleID: req.user.googleID}).save(function(err, data){
if (err) throw err;
res.json(data);
})
});
app.delete("/todo/:item", function(req, res){
// delete requested item from the database
Todo.find({item: req.params.item.replace(/\-/g, " ")}).remove(function(err, data){
if(err) throw err;
res.json(data);
});
});
};
todo-model.js
const mongoose = require("mongoose");
const todoSchema = new mongoose.Schema({
todo: String,
googleID: String
});
const Todo = mongoose.model("Todo", todoSchema);
module.exports = Todo;
istening on port 3000
(node:2656) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
connected to mongodb server
connected to mongodb server
TypeError: Cannot read property 'googleID' of undefined
答案 0 :(得分:0)
如果user
是您发送到请求正文中的API(我做了这个结论,因为我没有在代码段中看到passportjs
的用法),那么您会收到此错误,因为您使用req.user.googleID
而不是req.body.user.googleID
。 bodyParser
从HTTP请求的正文中解析JSON,并将其放在req.body
下。
答案 1 :(得分:0)
发现了问题,我打电话给req.body而不是req.body.item。我必须调用item,因为我现在将两个item推送到数据库中了,但是现在可以正常工作了,我意识到在CS类中途可以使用一个数据库