我是NoSQLMongoDB的新手,我需要在数据库中的一个集合上写一个插入事件的触发器,如下所示。数据库名称:GiftShop GiftShop Collection Name: GiftsGiftsGifts的模式是如下的:-
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 compass插入一个新的礼物,它连接到我的MongoDB atlas,但是我的通知集合没有被通知的模式中提到的数据填充。我到底哪里出错了,根据我的要求写触发器的正确方法是什么?谢谢你。
有一些调试拼接函数的要点。此处你应该可以按照这些来判断是你的功能问题还是触发器的问题。