首页 文章

创建脚本以将种子数据插入node.js中的mongodb

提问于
浏览
0

我正在使用mongoose和node.js(express),我希望使用脚本插入种子数据 . 就像我做节点脚本/ createNotifications.js一样,我可以将数据插入到我的数据库中 .

我的代码

//createNotifications.js
const mongoose = require('mongoose')
const Notification = require('../api/models/notificationModel')
mongoose.Promise = global.Promise

module.exports = (async () => {

    try {

        const new_notification = await new Notification({ 
            "userId" : mongoose.Types.ObjectId("5a3e76ce914e1d1bd854451d"),
            "msg" : "Something"
        }).save()

    } catch(e) {
        console.log('Error creating notifications. ', e)
    }
})()

当我运行代码时,我没有看到任何数据被插入 . 我的服务器在端口3000中启动,我是否必须在此文件中连接到mongodb?因为这个文件与我的快递应用程序无关,所以它只是一个单独的文件 .

1 回答

  • 0

    如果你想看到 module 正在运行,请确保以下内容

    • 确保您已与数据库 Build 连接,如 mongoose.connect('mongodb://IP/DBName')

    • 你自己执行的是什么 . 您必须在邮件文件中使用 require 此模块,使用 node 运行的文件,例如 node server.js 并调用该方法 . 就像是

    var notification = require(path/to/createNotifications);
    notification();
    

相关问题