2017-10-11 68 views
0

我正在学习Express.js,MongoDB和Mongoose,并且我正在创建一个小应用程序,让我可以将项目存储到列表中。 我想创建一个GET /列表/搜索路线,它允许搜索列表中的项目,但我还没有得到它的工作。 这里是我的代码猫鼬:如何用mongoose搜索mongoDB

路线

const express = require('express'); 

router = express.Router(); 

const db = require("../models"); 

router.get('/', function(req, res, next){ 
    db.List.find().then(function(list){ 
     res.render('index', {list}); 
    }); 
}); 

router.get('/new', function(req, res, next){ 
    res.render('new'); 
}); 

router.get('/:id', function(req, res, next){ 
    db.List.findById(req.params.id).then(function(list){ 
     res.render('show', {list}); 
    }); 
}); 

router.get('/:id/edit', function(req, res, next){ 
    db.List.findById(req.params.id).then(function(list){ 
     res.render('edit', {list}); 
    }); 
}); 

router.get('/search', function(req, res, next){ 
    db.List.findOne(req.query.search).then(function(list){ 
     console.log(list); 
     res.render('show', {list}); 
    }); 
}); 

router.post('/', function(req, res, next){ 
    db.List.create(req.body).then(function(list){ 
     res.redirect('/'); 
    }); 
}); 

router.patch('/:id', function(req, res, next){ 
    db.List.findByIdAndUpdate(req.params.id, req.body).then(function(list){ 
     res.redirect('/'); 
    }); 
}); 

router.delete('/:id', function(req, res, next){ 
    db.List.findByIdAndRemove(req.params.id).then(function(list){ 
     res.redirect('/'); 
    }); 
}); 

module.exports = router;  

Index.pug 延伸base.pug

block content 
h1 My List 
form(action="/list/search" method="GET") 
    input(type="text" name="search") 
    input(type="submit", value="search") 
a(href="/list/new") Add New Item! 
each item in list 
    p ITEM: #{item.name} QUANTITY: #{item.quantity}  
      a(href=`/list/${item.id}/edit`) Edit 

我的主要问题是GET /搜索,我想将搜索查询传递到搜索框并将结果返回给渲染文件

router.get('/search', function(req, res, next){ 
     db.List.findOne(req.query.search).then(function(list){ 
      console.log(list); 
      res.render('show', {list}); 
     }); 
    }); 

在此先感谢

回答

0

你需要指定的参数as attributes in the query。如果没有找到匹配的记录,list将为null

router.get('/search', function (req, res, next) { 
    db.List.findOne({ 
    name: req.query.name, 
    age: req.query.age 
    }).then(function (list) { 
    console.log(list); 
    if (list === null) { 
     return res.render('show', { 
     list: [] 
     }); 
    } 
    return res.render('show', { 
     list: list 
    }); 
    }).catch((err) => { 
    console.log('err', err); 
    return res.render('show', { 
     list: [] 
    }); 
    }); 
});