1

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()
});
0

1 Answer 1

3

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);
  docs.map(license => {
     license.sendGreetings()
  });
}

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

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.