【问题标题】:How to execute a script in Mongoose running Mongodb?如何在运行 Mongodb 的 Mongoose 中执行脚本?
【发布时间】:2020-05-11 23:18:59
【问题描述】:

我正在尝试通过节点控制台或仅通过命令行将以下内容作为脚本运行。 但似乎不起作用,我错过了什么?

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

【问题讨论】:

    标签: javascript node.js mongodb mongoose schema


    【解决方案1】:

    你应该更新你的代码,因为它的承诺请求!

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

    更多了解find() in mongooes read this link 并制作脚本

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-06
      • 2018-04-15
      • 2020-12-08
      • 1970-01-01
      • 2011-10-01
      • 2018-03-31
      • 2014-12-07
      • 2020-02-10
      相关资源
      最近更新 更多