繁体   English   中英

如何从 mongoose model 中的另一个 model 访问字段

[英]How can i access field from another model in mongoose model

我在这里做了两个 MongoDB 型号

电影 Model

import mongoose from 'mongoose';

const movieSchema = new mongoose.Schema({
  title: {
    type: String,
    required: [true, 'Please Enter the Movie Title'],
    trim: true,
    minlength: 5,
    maxlength: 255
  },
  genre: {
    type: mongoose.Schema.ObjectId,
    ref: 'Genre',
    required: true
  },
  year: {
    type: Number,
    min: 1800,
    max: 3000,
    required: [true, 'Please enter the year of the movie.']
  },
  directors: [
    {
      type: String,
      minlength: 5,
      maxlength: 100
    }
  ],
  writers: [
    {
      type: String,
      minlength: 5,
      maxlength: 100
    }
  ],
  cast: [
    {
      type: String,
      minlength: 5,
      maxlength: 100
    }
  ],
  numberInStock: {
    type: Number,
    required: true,
    min: 0,
    max: 255
  },
  dailyRentalRate: {
    type: Number,
    required: true,
    min: 0,
    max: 255
  }
});

export default mongoose.model('Movie', movieSchema);

出租 Model

import mongoose from 'mongoose';
import moment from 'moment';

const rentalSchema = new mongoose.Schema({
  customer: {
    type: mongoose.Schema.ObjectId,
    ref: 'Customer',
    required: true
  },
  movie: {
    type: mongoose.Schema.ObjectId,
    ref: 'Movie',
    required: true
  },
  dateOut: {
    type: Date,
    required: true,
    default: Date.now
  },
  dateReturned: {
    type: Date
  },
  rentalFee: {
    type: Number,
    min: 0
  }
});


rentalSchema.methods.return = function () {
  this.dateReturned = new Date();

  this.rentalFee =
    moment().diff(this.dateOut, 'days') * this.movie.dailyRentalRate;
};

export default mongoose.model('Rental', rentalSchema);

返回 Controller

import catchAsync from '../utils/catchAsync.js';
import AppError from '../utils/appError.js';
import Rental from '../models/rentalModel.js';
import Movie from '../models/movieModel.js';

const returns = catchAsync(async (req, res, next) => {
  const rental = await Rental.findOne({
    customer: req.body.customerID,
    movie: req.body.movieID
  });
  // console.log(rental);
  if (!rental) {
    return next(new AppError('Not Found', 400));
  }

  if (rental.dateReturned) {
    return next(new AppError('Already Returned', 400));
  }

  rental.return();
  await rental.save();
  // add movie back into stock
  await Movie.updateOne(
    { _id: rental.movie._id },
    {
      $inc: { numberInStock: 1 }
    }
  );

  res.status(400).json({
    status: 'success',
    rental
  });
});

export default returns;

回程路线

import { Router } from 'express';
import { protect } from '../controllers/authController.js';
import returns from '../controllers/returnController.js';

const router = Router();

router.post('/', protect, returns);

export default router;

问题是,当我想访问 Rental Model 中的电影字段时,它将返回电影 ID,但我希望它返回 object 包含电影数据(类似于填充但在 ZA559B87068921EEC7this.49Logic so.485 内) movie.dailyRentalRate 它返回的值不是未定义的

MongoDB 具有$lookup aggregation运算符。 ZCCADCDEDB567ABAE643E15DCF0974E503Z 有一个名为populate()替代方法,它可以让您参考其他 collections 中的文档。Population 是使用其他集合中的文档自动替换文档中指定路径的过程,因此您可以使用填充来解决您的问题,例如这个:

 const rental = await Rental.findOne({
    customer: req.body.customerID,
    movie: req.body.movieID
  }).populate("movie")

它对我有用,并且在methods.return中,您可以访问this.movie.dailyRentalRate

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM