我有三个集合和架构:用户、产品和订单。以及三个架构:
const User = new Schema({
username: {
type: String,
required: true,
},
)};
const Product = new Schema({
name: {
type: String,
required: true,
},
)};
const Order = new Schema({
product: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product',
required: true,
},
User: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true,
},
quantity: {
type: Number,
required: true,
},
)};
要获取嵌套对象,我使用 Product.find().populate('user product')
。
但是,在产品列表中,我使用聚合进行分页,而不是使用查找。聚合中的 populate 相当于什么?因为我已经测试过查找,但它不起作用。
let filter = {};
let data = [];
let total = [{ total: 0 }];
filter = { user: mongoose.Types.ObjectId(req.user.id) };
data = await Product.aggregate([
{
$match: filter,
},
{
$lookup: {
from: 'users',
localField: 'user',
foreignField: '_id',
as: 'user',
},
},
{ $unwind: '$user' },
{
$project: {
'user.password': 0,
},
},
{
$match: {
$or: [
{ 'user.username': { $regex: search, $options: 'x,g,i' } },
],
},
},
{
$limit: limit,
},
]);
if (data.length > 0) {
total = await Product.aggregate([
{
$match: filter,
},
{
$lookup: {
from: 'users',
localField: 'user',
foreignField: '_id',
as: 'user',
},
},
{ $unwind: '$user' },
{
$match: {
$or: [
{ 'user.username': { $regex: search, $options: 'x,g,i' } },
],
},
},
{
$count: 'total',
},
]);
}
我看到过与同一问题相关的其他问题,但似乎没有一个对我有用,如果您能帮我解决这个问题,我将不胜感激,谢谢!