1

I'm using mongoose and node.js (express), and I wish to insert seed data using script. Like when I do node scripts/createNotifications.js I can insert a data into my db.

My code

//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)
    }
})()

When I run the code I don't see any data been inserted. I have my server started in port 3000, do I have to connect to mongodb too in this file? since this file has nothing to do with my express app, it's just a separated file.

8
  • where are you calling this method ? have you made connection with db ? Commented May 6, 2018 at 1:37
  • When you run what code? All that is here is a module declaration with an assigned IIFE. This code itself is not executable. I think really you don't actually mean to assign to the module.exports and are simply doing "rote copy" because you don't really know what that means. Also of course. No connection attempt at all Commented May 6, 2018 at 1:38
  • @GeorgeBailey nope, I run it in my terminal. Commented May 6, 2018 at 1:42
  • @NeilLunn if I do a http request it will execute. Commented May 6, 2018 at 1:43
  • 1
    "Connection to the database". You need to call mongoose.connect() in order to do anything. The code here does nothing without that. Commented May 6, 2018 at 1:44

1 Answer 1

1

If you want to see this module running make sure the following

  1. Make sure you've made connection with the database like mongoose.connect('mongodb://IP/DBName')
  2. What you've posted above is just a module definition. It won't execute on its own. You'll have to require this module in your mail file, the file you're running with node for example node server.js and call the method. Something like

    var notification = require(path/to/createNotifications);
    notification();
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.