如何使用另一个模型的节点js从猫鼬的字段中获取聚合

时间:2020-06-01 06:04:46

标签: node.js json mongoose aggregate

我有两个模型架构 productPerDay和productPerMonth

// Model 1 that input data every day
const productPerDay = new mongoose.Schema({
   product : String,
   price : Number,
   month : {
       type : String
       default : () => moment(Date.now()).tz('Asia/Jakarta').locale('id').format('MMMM')
   }
}, {
    timestamps : {
       currentTime: () => moment(Date.now()).tz('Asia/Jakarta').locale('id').format('YYYY-MM-Do LT')
     }
});

//Model 2 That input data every month and get aggregate for total price field from price data model1 that input every day
const productPerMonth = new mongoose.Schema({
    product : String,
    totalPrice : Number,
    month : {
       default : () => moment(Date.now()).tz('Asia/Jakarta').locale('id').format('MMMM')
     }
}, {
    timestamps : {
       currentTime: () => moment(Date.now()).tz('Asia/Jakarta').locale('id').format('YYYY-MM-Do LT')
    }
});

我期望的结果是这样的

//From Model 1
[
    {
        "product" : "book",
        "price" : 5000,
        "month" : "May"
    },
    {
        "product" : "book",
        "price" : 10000,
        "month" : "May"
    }
    {
        "product" : "pen",
        "price" : 100,
        "month" : "June"
    },
    {
        "product" : "pen",
        "price" : 200,
        "month" : "June"
    }
]

//From Model 2
[
    {
        "product" : "book",
        "month" : "may",
        "totalPrice" : 15000
    },
    {
        "product" : "pen",
        "month" : "June",
        "totalPrice" : 300
    }
]

我尝试像这样在Nodejs中发布并从Model 1中获取结果

// router to post and get data each day
router.post('/productPerDay', async (req,res) => {
    const product = new ProductPerDayModels({});
    try {
        await ProductPerDayModels.save();
        res.status(201).json(product);
    } catch (e) {
        res.status(400).send(e);
    }
});

router.get('/productPerDay', async (req,res) => {
    try {
        const product = await ProductPerDayModels.find([]);
        res.json(product);
    } catch (e) {
        res.status(400).send(e);
    }
});

我想从模型1中填写的每个价格数据中获取模型2中totalPrice字段的数据,并将每个月的数据以相同的方式加在一起

//router 2 to get and post each month
router.post('/productPerMonth', async (req,res) => {
    const product = new ProductPerMonthModels({
        ...req.body,
        totalPrice : //what should i do here to get totalPrice from price fields in model 1?
    });
    try {
        await ProductPerMonthModels.save();
        res.status(201).json(product);
    } catch (e) {
        res.status(400).send(e);
    }
});

router.get('/productPerMonth', async (req,res) => {
    try {
        const product = await ProductPerMonthModels.find([]);
        res.json(product);
    } catch (e) {
        res.status(400).send(e);
    }
});

请指导我解决此问题,或告诉我解决它的错误。谢谢

0 个答案:

没有答案
相关问题