首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >猫鼬:如何用猫鼬搜索mongoDB

猫鼬:如何用猫鼬搜索mongoDB
EN

Stack Overflow用户
提问于 2017-10-11 11:10:58
回答 1查看 118关注 0票数 0

我正在学习Express.js、MongoDB和Mongoose,我正在创建一个小应用程序,它允许我将项目存储到列表中。我正在尝试创建一个GET / list /search路径,它允许搜索列表中的项目,但我还没有让它开始工作。这是我的密码

路由

代码语言:javascript
复制
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

代码语言:javascript
复制
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 /search,我想将搜索查询传递到搜索框并将结果返回给呈现文件。

代码语言:javascript
复制
router.get('/search', function(req, res, next){
        db.List.findOne(req.query.search).then(function(list){
            console.log(list);
            res.render('show', {list});
        });
    });

提前感谢

EN

回答 1

Stack Overflow用户

发布于 2017-10-12 08:27:37

您需要指定参数作为查询中的属性。如果没有找到匹配的记录,list将是null

代码语言:javascript
复制
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: []
    });
  });
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46686746

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档