findByID不是一个函数

时间:2018-06-10 02:53:15

标签: node.js express mongoose

列出项目

var express = require("express");
var app = express();
var Mongoose = require("Mongoose");

Mongoose.connect("mongodb://localhost/YelpCamp_app"); 

var YelpCampSchema = new Mongoose.Schema({
  name:String,
  image:String,
  description:String
});

var YelpCamp = Mongoose.model("YelpCamp",YelpCampSchema);

app.get('/campgrounds/:id',function(req,res){
  YelpCamp.findByID(req.params.id, function(err,campground) {
    if(err) {
      console.log("error");
    } else {
      res.render("show.ejs");
    }
  });
});

我收到的错误是findByID不是函数

2 个答案:

答案 0 :(得分:2)

findById不是findByID

app.get('/campgrounds/:id',function(req,res){
  YelpCamp.findById(req.params.id, (err,campground) => {
    if(err) {
      console.log("error");
    } else {
      res.render("show.ejs");
    }
  });
});

有关详情,请访问:http://mongoosejs.com/docs/api.html#findbyid_findById

答案 1 :(得分:0)

你应该要求' mongoose'而不是猫鼬'。之后,您可以使用findById检索单个YelpCamp,如下所示:

var express = require("express");
    var app = express();
    const mongoose = require('mongoose');
    mongoose.connect("mongodb://localhost/YelpCamp_app"); 
    const YelpCampSchema  = mongoose.Schema({
        name:String,
      image:String,
      description:String
    });
    var YelpCamp = mongoose.model("YelpCamp",YelpCampSchema);
    app.get('/campgrounds/:id',function(req,res){
    YelpCamp.findById(req.params.id)
        .then(data => {
            if(!data) {
                console.log("data not found");            
            }
            res.render("show.ejs");
        }).catch(err => {

          console.log("error");

        });
    });