首页 > 解决方案 > 如何在 mongodb atlas 中创建插入触发器?

问题描述

我是 NoSQL/MongoDB 的新手,我需要在我的数据库中的一个集合上编写一个插入事件触发器,如下所示: 数据库名称:GiftShop 集合名称:Gifts Gifts 架构如下:-

const mongoose = require("mongoose");
const userModel = require('./userModel');
const imageModel = require('./imageModel');
const giftSchema = mongoose.Schema({
        name: String,
        availableQuantity: Number,
        price: Number,
        Seller: {type: mongoose.Schema.Types.ObjectId,ref: 'UserModel'},
        imageName: {type: mongoose.Schema.Types.ObjectId,ref: 'ImageModel'},
        deliveryInDays: Number,category: [{type: String, ref: 'CategoryModel'}]
        }, {collection: "gifts"});
module.exports = giftSchema;

我有另一个名为通知的集合。我想创建一个这样的触发器,只要将新礼物插入礼物集合中,通知集合就必须填充以下信息:礼物 ID、卖家 ID、买家 ID 数组。

通知的架构如下:

const mongoose = require("mongoose");
const notificationSchema = mongoose.Schema({
        seller: { type: mongoose.Schema.Types.ObjectId,ref: 'UserModel'},
        buyer: [{type: mongoose.Schema.Types.ObjectId,ref: 'UserModel'}],
        newGift: {type: mongoose.Schema.Types.ObjectId,ref: 'GiftModel'}
        }, {collection: "notifications"});
module.exports = notificationSchema;

以下是我在 MongoDB atlas 中编写的函数,但它有很多问题:

exports = function (changeEvent) {
        const {fullDocument} = changeEvent;
        const {buyer, seller, newGift} = fullDocument;
        const collection = context.services.get("Cluster0").db("test").collection("notification");
return collection.insertOne({buyer, seller, newGift})};

我在 MongoDB atlas 上为创建触发器所做的设置: 在此处输入图像描述

在此处输入图像描述

我正在通过连接到我的 MongoDB 地图集的 MongoDB 指南针插入一个新礼物,但我的通知集合没有填充通知架构中提到的数据。我哪里错了?根据我的要求编写触发器的正确​​方法是什么?谢谢你。

标签: mongodbmongoosemongodb-querydatabase-triggermongodb-atlas

解决方案


这里有一些调试缝合功能的指示,您应该能够按照这些指示来确定问题出在您的功能还是触发器上。


推荐阅读