How to execute a script in Mongoose running Mongodb?

64
January 26, 2020, at 11:00 PM

I'm trying to run the following as a script through either node console or just the command line. But doesn't seem to be working, what am I missing?

const mongoose = require("mongoose");
const ENV = require('dotenv').parse(envStr)

mongoose.connect(
  ENV.MONGO_URL,
  function(err) {
    if (err) throw err;
    console.log('connected');
  },
)
const UserSchema = ({
  name: String,
  messages: [Messages], // this part is working when I run tests...
  ...
})
UserSchema.methods.sendGreetings = function() {
  this.messages.push(
    new Message({
      msg: 'Hello!'
    })
  )
}
const User = new mongoose.Model('User', UserSchema)

const all = User.find({});
debugger // not working
all.map(user => {
  debugger; // not working
  user.sendGreetings()
});
Answer 1

you should update your code, because its promise request!

const mongoose = require('mongoose');
const ENV = require('dotenv').parse(envStr)
run().catch(error => console.log(error.stack));
async function run() {
  await mongoose.connect(ENV.MONGO_URL, { useNewUrlParser: true });
  // Clear the database every time. This is for the sake of example only,
  // don't do this in prod :)
  await mongoose.connection.dropDatabase();
  const customerSchema = new mongoose.Schema({ name: String, messages: [Messages], ... });
  const User = mongoose.model('User', UserSchema);
  //await User.create({ name: 'A', messages: [30, 10] });
  //await User.create({ name: 'B', messages: [28, 10] });
  // add your data in your Schema
  // Find all User
  const docs = await User.find();
  console.log(docs);
  all.map(license => {
     license.sendGreetings()
  });
}

for more learning about find() in mongooes read this link and make script

READ ALSO
Not able to attach the emoji to textbox

Not able to attach the emoji to textbox

I am using Emoji mart with react but it is not getting attached with Textbox

52
Write a function that will return the two number array combination with value summed at 5. I can't get all the opportunities

Write a function that will return the two number array combination with value summed at 5. I can't get all the opportunities

A job posting wants me to write a an answer to a question which if I solve I am eligible for the next rownd

34
Download files(Electron)

Download files(Electron)

I need to download files through the Electron appFiles are voluminous, weigh about 2

65