find函数在指定字段的mongoose中不起作用

时间:2017-06-02 20:14:27

标签: javascript node.js mongodb express mongoose

所以我正在制作这个网站,你可以看到不同的食谱。在浏览食谱时,我希望用户能够选择一个类别并浏览其下的所有菜肴(即甜点,晚餐,素食等)。

我在路由器文件中创建了这个函数,它返回属于指定类别的所有菜肴:

router.get('/showrecipes/:categoryname', (req, res, next) => {

    let nameQuery = {category: req.params.categoryname};

    Recipe.find(nameQuery, (err, recipes) => {
        if (err) throw err;

        res.json(recipes);
    });
});

但是,当我尝试在Postman中测试它时,我会继续使用Null而不是所有属于该类别的菜肴。 enter image description here

我的所有其他功能都正常工作,但这个功能似乎有问题。

供参考,这是recipeRouter文件的其余部分:

const express = require('express');
const passport = require('passport');
const Recipe = require('../models/recipe');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');


router = express.Router();

router.get('/', (req, res, next) => {
  res.json('Here are the recipes!')
});

// Is working

router.get('/showrecipes', (req, res, next) => {
  Recipe.find({}, (err, recipes) => {
    if (err) throw err;
    res.json(recipes);
  });
});

// Is working.

router.get("/showrecipes/:recipename", (req, res, next) => {
    let nameQuery = {name: req.params.recipename};

    Recipe.findOne(nameQuery, (err, recipes) => {
        if (err) throw err;

        res.json(recipes);
    })
});

// Is not crashing, but is returning Null which isn't how it's supposed to work.

router.get('/showrecipes/:categoryname', (req, res, next) => {

    let nameQuery = {category: req.params.categoryname};

    Recipe.find(nameQuery, (err, recipes) => {
        if (err) throw err;

        res.json(recipes);
    });
});



// Now it's working, good stuff.

router.post('/addrecipe', (req, res, next) => {
  Recipe.create({
      name: req.body.name,
      description: req.body.description,
      steps: req.body.steps,
      ingredients: req.body.ingredients,
      category: req.body.category,
  }, (err, recipe) => {
    if (err) throw err;

    // Recipe.save();

    res.json(recipe);
  });
});

// See if this works

router.put('editrecipe/:recipename/:editedField', (req, res, next) => {

    Recipe.findOneAndUpdate({name: req.params.recipename}, {$set: req.body}, {new: true}, (err, recipe) => {
        if (err) throw err;

        res.json(recipe)

    });
});

// It's working, thank god

router.delete('/deleterecipe/:recipename', (req, res, next) => {

    let nameQuery = {name: req.params.recipename};

    Recipe.findOneAndRemove(nameQuery, (err, recipe) => {
        if (err) throw err;

        res.send('Dish was succesfully deleted!')
    });

});


module.exports = router;

这是我的app.js文件

let express = require('express');
let mongoose = require('mongoose');
let path = require('path');
let bodyParser = require('body-parser');
let recipeRouter = require('./routes/recipeRouter');
let userRouter = require('./routes/userRouter');
let bcrypt = require('bcrypt');
let passport = require('passport');
let LocalStrategy = require('passport-local').Strategy;
let config = require('./config');

mongoose.connect(config.mongoUrl);

let db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function () {
    // we're connected!
    console.log("Connected correctly to server");
});

const app = express();

const port = 3000;

app.listen(port);

app.use(express.static(path.join(__dirname, 'public')));

app.use(bodyParser.json());

app.set('views', path.join(__dirname, 'views'));

app.use('/users', userRouter);
app.use('/recipes',recipeRouter);

app.get('/', function(req, res){
  res.send('Hey, this is your database!')
});


module.exports = app;

这是我的食谱文件

const express = require('express');
const mongoose = require('mongoose');
const User = require('../models/user');

let Schema = mongoose.Schema;

let commentSchema = Schema({

  rating: {
    type: Number,
    required: true,
    min: 1,
    max: 5,
  },

  comment: {
    type: String,
    required: true
  },

  postedBy: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  }
});

let Comment = mongoose.model('Comment', commentSchema);

let recipeSchema = Schema({

  name: {
    type: String,
    required: true
  },

  description: {
    type: String,
  },

  steps: {
    type: String,
    required: true,
  },

  ingredients: {
    type: Array,
    required: true
  },

  comments: [commentSchema],

  category: {
    type: String,
    required: true,
  },

  postedBy: {
    type: Schema.Types.ObjectId,
    ref: 'User'
  }

});

/// So I learnt that by defining the string as "Recipe" in the model function, I will have to lower case it
/// and pluralize it when I use it with res.json and other such things (i.e. "Recipe" => recipes).

let Recipe = mongoose.model('Recipe', recipeSchema);

module.exports = Recipe;

/// refactor this so that these are in the router, not in the models file

/*

module.exports.getRecipeByName = (name, callback) => {
  let nameQuery = {name: name};
  Recipe.findOne(nameQuery, callback);
};

module.exports.getRecipesByCategory = (category, callback) => {
  Recipe.find({'category': category});
};

*/

0 个答案:

没有答案