You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于Mongoose与Node.js(Express)编写MongoDB种子数据插入脚本

Got it, let's get this notification seed script working properly with Mongoose and Express. Here's how to tweak your existing code so you can run node scripts/createNotifications.js and populate your MongoDB with sample notifications:

Fixing Your Mongoose Notification Seed Script

First, your current code is an exported async function that won't run on its own, and it's missing the critical MongoDB connection step. Let's build out a complete, working version:

Full Working Script (scripts/createNotifications.js)

const mongoose = require('mongoose');
const Notification = require('../api/models/notificationModel');

// Set Mongoose to use global promises
mongoose.Promise = global.Promise;

// Replace with your actual MongoDB connection URI
const DB_URI = 'mongodb://localhost:27017/your-app-database';

async function seedNotifications() {
  try {
    // Connect to the database first
    await mongoose.connect(DB_URI);
    console.log('✅ Connected to MongoDB successfully');

    // Define your seed notification data (add as many entries as needed)
    const seedData = [
      {
        userId: mongoose.Types.ObjectId("5a3e76ce914e1d1bd854451d"),
        msg: "Your order has been shipped!",
        read: false,
        createdAt: new Date()
      },
      {
        userId: mongoose.Types.ObjectId("5a3e76ce914e1d1bd854451d"),
        msg: "You have a new message from support",
        read: false,
        createdAt: new Date()
      }
    ];

    // Bulk insert the notifications for efficiency
    const insertedDocs = await Notification.insertMany(seedData);
    console.log(`✅ Successfully inserted ${insertedDocs.length} notifications`);

  } catch (err) {
    console.error('❌ Error seeding notifications:', err);
  } finally {
    // Always close the connection to avoid hanging Node processes
    await mongoose.disconnect();
    console.log('🔌 Disconnected from MongoDB');
  }
}

// Run the seed function immediately when the script is executed
seedNotifications();

Key Improvements Made

  • Database Connection: Added explicit connection logic—replace your-app-database with your actual database name, or update the URI if using a remote cluster (like MongoDB Atlas).
  • Self-Executing Logic: Instead of exporting the function, we run seedNotifications() directly so the script executes as soon as you run the command.
  • Bulk Insert: Used insertMany() instead of creating individual documents for better performance, especially with multiple seed entries.
  • Clean Connection Handling: Added a finally block to disconnect from MongoDB after the operation finishes, preventing Node from keeping the process open unnecessarily.
  • Clear Logging: Added success/error messages to make debugging easier if something goes wrong.

How to Run the Script

Just execute this command in your terminal:

node scripts/createNotifications.js

Quick Notes

  • Ensure your MongoDB server is running locally (or update the DB URI to point to your remote cluster).
  • Double-check that your notificationModel.js schema matches the fields in your seed data (e.g., userId, msg, read, createdAt).
  • If you want to avoid duplicate entries on repeated runs, you could add a pre-seed cleanup step (like deleting existing notifications) or use updateOne() with upsert: true instead of insertMany().

内容的提问来源于stack exchange,提问作者Madeline Ries

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:31:31