簡體   English   中英

TypeError:模式路徑“genre.type”的值無效,得到值“未定義”。 請幫我

[英]TypeError: Invalid value for schema path `genre.type`, got value “undefined”. Please help me

我正在學習 Node.js 並嘗試為電影租賃服務構建一個簡單的應用程序。 這是我為電影定義模式的代碼,它拋出了一個錯誤。

const Joi = require('joi');
const mongoose = require('mongoose');
const {genreSchema} = require('./genre');
 
//the below line thorws error and terminal points cursor at "new"
const Movie = mongoose.model('Movies',new mongoose.Schema({     
    type: String,
    required: true,
    trim: true, 
    minlength: 5,
    maxlength: 255
  },
  genre: { 
    type: genreSchema,  
    required: true
  },
  numberInStock: { 
    type: Number, 
    required: true,
    min: 0,
    max: 255
  },
  dailyRentalRate: { 
    type: Number, 
    required: true,
    min: 0,
    max: 255
  }
}));

function validateMovie(movie) {
  const schema = {
    title: Joi.string().min(5).max(50).required(),
    genreId: Joi.objectId().required(),
    numberInStock: Joi.number().min(0).required(),
    dailyRentalRate: Joi.number().min(0).required()
  };

  return Joi.validate(movie, schema);
}

exports.Movie = Movie; 
exports.validate = validateMovie;

這是./genre 請檢查一下。

const mongoose = require('mongoose');
const Joi = require('joi');
const genreSchema = new mongoose.Schema({
    name:{
        type:String,
        required:true,
        minlength: 5,
        maxlength: 50
    }
})
const Genre = mongoose.model('Genre', genreSchema);
function validateGenre(genre){
    const schema = {
        name: Joi.string().min(3).required()
    };
    
     return Joi.validate(genre,schema);
}
exports.Genre=Genre;
exports.validate = validateGenre;

這是./rentals文件。 它還拋出“Object.anonymous”錯誤。

const { Rental, validate } = require('../models/rental');
const { Movie } = require('../models/movie');
const { Customer } = require('../models/customer');
const auth = require('../middleware/auth');
const mongoose = require('mongoose');
const Fawn = require('fawn');
const express = require('express');
const router = express.Router();

Fawn.init(mongoose);

router.get('/', auth, async (req, res) => {
  const rentals = await Rental.find()
    .select('-__v')
    .sort('-dateOut');
  res.send(rentals);
});
router.post('/', auth, async (req, res) => {
  const { error } = validate(req.body);
  if (error) return res.status(400).send(error.details[0].message);

  const customer = await Customer.findById(req.body.customerId);
  if (!customer) return res.status(400).send('Invalid customer.');

  const movie = await Movie.findById(req.body.movieId);
  if (!movie) return res.status(400).send('Invalid movie.');

  if (movie.numberInStock === 0)
    return res.status(400).send('Movie not in stock.');

  let rental = new Rental({
    customer: {
      _id: customer._id,
      name: customer.name,
      phone: customer.phone
    },
    movie: {
      _id: movie._id,
      title: movie.title,
      dailyRentalRate: movie.dailyRentalRate
    }
  });

  try {
    new Fawn.Task()
      .save('rentals', rental)
      .update('movies',{ _id: movie._id },{
          $inc: { numberInStock: -1 }
        })
      .run();

    res.send(rental);
  } 
  catch (ex) {
    res.status(500).send('Something failed.');
  }
});

router.get('/:id', [auth], async (req, res) => {
  const rental = await Rental.findById(req.params.id).select('-__v');

  if (!rental)
    return res.status(404).send('The rental with the given ID was not found.');

  res.send(rental);
});

module.exports = router;

這是我收到的錯誤消息。 我在 Windows 上,我的文本編輯器是 VScode,終端是 powershell

PS D:\Study\Vidly> node index.js
D:\Study\Vidly\node_modules\mongoose\lib\schema.js:475
      throw new TypeError('Invalid value for schema path `' + fullPath +
      ^

TypeError: Invalid value for schema path `genre.type`, got value "undefined"
    at Schema.add (D:\Study\Vidly\node_modules\mongoose\lib\schema.js:475:13)
    at Schema.add (D:\Study\Vidly\node_modules\mongoose\lib\schema.js:509:12)
    at new Schema (D:\Study\Vidly\node_modules\mongoose\lib\schema.js:129:10)
    at Object.<anonymous> (D:\Study\Vidly\models\movie.js:5:39)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (D:\Study\Vidly\routes\rentals.js:2:19)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)

根據您的genre.js文件,您需要更改它

const {genreSchema} = require('./genre');

const {Genre} = require('./genre');

和這個:

  ...
  genre: { 
    type: genreSchema,  
    required: true
  },
  ...

  genre: { 
    type: Genre,
    required: true
  },

更改后的新錯誤消息

throw new TypeError(`Invalid schema configuration: \`${name}\` is not ` +
    ^

    TypeError: Invalid schema configuration: `Model` is not a valid type at path `genre`. 
        at Schema.interpretAsType (D:\Study\Vidly\node_modules\mongoose\lib\schema.js:1005:11)
        at Schema.path (D:\Study\Vidly\node_modules\mongoose\lib\schema.js:676:27)
        at Schema.add (D:\Study\Vidly\node_modules\mongoose\lib\schema.js:527:14)
        at new Schema (D:\Study\Vidly\node_modules\mongoose\lib\schema.js:129:10)
        at Object.<anonymous> (D:\Study\Vidly\models\movie.js:5:39)
        at Module._compile (internal/modules/cjs/loader.js:1063:30)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
        at Module.load (internal/modules/cjs/loader.js:928:32)
        at Function.Module._load (internal/modules/cjs/loader.js:769:14)
        at Module.require (internal/modules/cjs/loader.js:952:19)
        at require (internal/modules/cjs/helpers.js:88:18)
        at Object.<anonymous> (D:\Study\Vidly\routes\rentals.js:2:19)
        at Module._compile (internal/modules/cjs/loader.js:1063:30)
        at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
        at Module.load (internal/modules/cjs/loader.js:928:32)
        at Function.Module._load (internal/modules/cjs/loader.js:769:14)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM