我有一个 Booking
模型和一个 Event
模型。我正在尝试查询并检查是否有任何预订已具有特定的 Event._id
和 User._id
,以阻止创建重复的预订该用户和事件。聚合查询适用于 MongoDB 罗盘,但是当我在 Node.js 应用程序中尝试查询时,它只给我一个空数组
型号
预订
const BookingSchema = new Schema({
amount: {
type: Number,
required: 'Please supply a number of people',
},
event: {
type: mongoose.Schema.ObjectId,
ref: 'Event',
required: 'Must give an event!',
},
booker: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: 'You must supply the booker!',
},
confirmed: {
type: Boolean,
default: false,
},
});
事件
const eventSchema = new Schema(
{
title: {
type: String,
trim: true,
required: 'You must add an event name!',
},
description: {
type: String,
trim: true,
},
slug: String,
created: {
type: Date,
default: Date.now,
},
date: {
type: Date,
min: Date.now,
required: 'Please enter a valid event Date!',
},
minCapacity: {
type: Number,
required: 'Please enter a correct min capacity for your event!',
},
maxCapacity: {
type: Number,
required: 'Please enter a correct max capacity for your event!',
},
price: Number,
location: {
type: {
type: String,
default: 'Point',
},
coordinates: [
{
type: Number,
required: 'You must supply coords!',
},
],
address: {
type: String,
required: 'Please enter a valid address!',
},
},
photo: String,
author: {
type: Schema.ObjectId,
ref: 'User',
required: 'You must supply an author!',
},
available: Boolean,
// attendees: [User], you can do through virtuals
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);
eventSchema.virtual('bookings', {
ref: 'Booking', // what model is linked?
localField: '_id', //what field on model
foreignField: 'event', //which field on Booking?
});
module.exports = mongoose.model('Event', eventSchema);
查询
exports.createBooking = async (req, res) => {
req.body.booker = req.user._id;
req.body.event = req.params.id;
const bookings = await Booking.aggregate(
[
{
$match: {
event: req.params.id,
},
},
{ $count: 'bookings' },
],
);
return res.json(bookings);
};
感谢您的高级!如果您需要任何其他信息,请告诉我。
最佳答案
您必须将 id
从 String
转换为 ObjectId
const ObjectID = require('mongodb').ObjectID
[
{ "$match": {
"event": ObjectId(req.params.id),
}},
{ "$count": "bookings" },
]
关于javascript - 使用 $match 的聚合查询适用于 MongoDB Compass,但不适用于我的 Node.js 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55362384/