javascript - 我如何从猫鼬模型中的另一个模型访问字段
问题描述
我在这里做了两个 MongoDB 模型
电影模特
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);
租赁模式
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);
返回控制器
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;
问题是,当我想访问租赁模型中的电影字段时,它将返回电影 ID,但我希望它返回包含电影数据的对象(类似于填充但在模型逻辑内部),所以如果我尝试访问它。 movie.dailyRentalRate 它返回的值不是未定义的
解决方案
MongoDB 有$lookup
aggregation
运算符。Mongoose 有一个名为 的替代方法populate()
,它可以让您引用其他集合中的文档。Population 是自动将文档中的指定路径替换为其他集合中的文档的过程,因此您可以使用 populate 来解决您的问题,如下所示:
const rental = await Rental.findOne({
customer: req.body.customerID,
movie: req.body.movieID
}).populate("movie")
它对我有用,并且在methods.return
您访问this.movie.dailyRentalRate
推荐阅读
- java - 如何从java insert在postgresql中插入一个包含撇号(单引号)的值?
- java - 在后台加载图像、视频
- android - 使 activity_main-small 无法正常工作
- go - zip.NewReader(bytes.NewReader(), len) 是否需要关闭或自动收集垃圾?
- sql - Add DELETE to query that returns duplicate records | SQL Server
- mysql - SQL查询按名称平均
- javascript - 使用 CSS 和不使用 JavaScript 将可变文本长度调整到固定容器宽度
- html - How to show information by selecting a date from the list
- kubernetes - 从通用 Kibana UI 监控来自多个 Kubernetes 集群(使用 GCP 和 Kops)的 pod 日志
- angular - Prime NG:打字稿中的树propagateSelectionUp