Mongoose查询在Node / Express CRUD API中返回

时间:2016-01-25 12:19:04

标签: javascript node.js mongodb express mongoose

它适用于此admin.js路由的大多数情况,但.put()和delete()请求附近的.get()请求正确呈现并且数据在页面上可见,但是我的终端收到此错误

  

... /admin.js:91               res.render('admin',{title:post.title,body:post.body});                                               ^

     

TypeError:无法读取null

的属性'title'

尝试编辑或删除在表单上呈现的帖子时,收到“此wepage不可见”错误。所以它呈现良好然后崩溃。

这是admin.js路由。这可能是订购的问题吗?我不明白为什么会崩溃。

var express = require('express');
var router = express.Router();
var session = require('client-sessions');
var bcrypt = require('bcryptjs');

var mongoose = require('mongoose');
var User = mongoose.model('users');
var Post = mongoose.model('posts');
var Song = mongoose.model('songs');
var Project = mongoose.model('projects');

// check whether User is logged in
function requireLogin(req, res, next) {
    if (!req.user) {
        req.session.reset();
        res.redirect('/admin');
    } else {
        next();
    }
};

router
    // Register
    .get('/register', requireLogin, function(req, res) {
        res.render('register');
    })

    .post('/register', function(req, res) {
        new User({
            name: req.body.name,
            password: req.body.password
        })
        .save(function(err, user) {
            res.redirect('/admin');
        });
    })

    // Login
    .get('/', function(req, res) {
        res.render('login');
    })

    .post('/', function(req, res) {
        User.findOne({name: req.body.name}, function(err, user) {
            if (!user) {
                res.render('login', {error: 'User not found'});
            } else if (bcrypt.compareSync(req.body.password, user.password)) {
                req.session.user = user;
                res.redirect('/admin/dashboard');
            } else {
                res.render('login', {error: 'Incorrect Password'});
            }
        });
    })  

    // Admin dashboard
    .get('/dashboard', requireLogin, function(req, res) {
        res.render('admin');
    })

    .post('/dashboard', function(req, res) {
        // Depending on which form was filled, create new entry and redirect
        if (req.body.postTitle) {
            new Post({title: req.body.postTitle, body: req.body.body})
            .save(function(err, post) {
                res.redirect('/posts');
            });
        } else if (req.body.songTitle) {
            new Song({title: req.body.songTitle, arist: req.body.artist, link: req.body.link})
            .save(function(err, song) {
                res.redirect('/music');
            });
        } else if (req.body.projectName) {
            new Project({
                name: req.body.projectName,
                picture: req.body.picture,
                languages: req.body.languages,
                summary: req.body.summary
            })
            .save(function(err, project) {
                res.redirect('/projects');
            });
        } else {
            res.redirect('/');
        }
    })

    .get('/dashboard/:title_slug', function(req, res) {
        var query = {'title_slug': req.params.title_slug};
        Post.findOne(query, function(err, post) {
            res.render('admin', {title: post.title, body: post.body});
        });
    })

    .put('/dashboard/:title_slug', function(req, res) {
        var query = {'title_slug': req.params.title_slug};
        var update = {'title': req.params.title, 'body': req.params.body};
        var options = {new: true};
        Post.findOneAndUpdate(query, update, options, function(err, post) {
            res.render('admin', 
                {
                    title: post.title,
                    body: post.body
                }
            );
        });
    })

    .delete('/dashboard/:title_slug', function(req, res) {
        var query = {'title_slug': req.params.title_slug};
        Post.findOneAndRemove(query, function(err, post) {
            res.redirect('/');
        });
    })

    // Logout
    .get('/logout', function(req, res) {
        req.session.reset();
        res.redirect('/admin');
    });

module.exports = router;

admin.html

中DELETE请求的表单示例
<div class='form posts-form'>
    <h2>Posts</h2>
    <form method='post' id='post' action'/admin/dashboard/{{post.title_slug}}?_method=DELETE'>
        <label>Title</label>
        <input type='text' name='postTitle' value='{{title}}'></br>
        <label>Body</label>
        <textarea name='body' form='post'>{{body}}</textarea></br>
        <button type='submit'>Delete</button>
    </form> 
</div>

1 个答案:

答案 0 :(得分:2)

同时检查是否(!post){console.log(&#34;找不到帖子&#34;)}。因为看起来没有找到任何项目,并且您正试图在未建立的对象上获得标题。

Post.findOne(query, function(err, post) {
    if (err)
       console.log(err);
    if (!post)
       console.log("not found")
    else
       res.render('admin', {title: post.title, body: post.body});
});