如何检查猫鼬中是否存在引用的子文档?

时间:2020-10-29 14:02:00

标签: mongoose mongodb-query

在添加关系之前寻求帮助以找出参考文档是否存在。站点文档与Campaign文档具有参考关系。在添加对关系的引用之前,我想检查文档,广告系列是否已被引用。

const mongoose = require("mongoose");

const SiteSchema = new mongoose.Schema({
domain: { type: String, required: true },
campaigns: [
    {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Campaign",
    },
],
});

module.exports = mongoose.model("Site", SiteSchema);

创建网站的代码:

  Mutation: {
    createSite: async (__, { input }) => {
        try {
            const { domain, campaignId } = input;
            
            // check if the domain already exist
            const siteExist = await Site.findOne({ domain: domain });

            if (siteExist) {
                // check if the campaign already added 
                // I need help here 
                const campaignExist = // here I need help 
                
                 if (!campaignExist) {
                    siteExist.campaigns.push(campaignId);
                    siteExist.save();
                }
                return siteExist;
                }

            // it is a new domain. Create a new record for it
            const site = await Site.create({
                domain,
                campaignId,
            });
            return site;
        } catch (error) {
            throw new Error(error);
        }
    }

0 个答案:

没有答案