javascript - 如何在运行 Mongodb 的 Mongoose 中执行脚本?

标签 javascript node.js mongodb mongoose schema

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

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

最佳答案

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

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

了解有关 mongooesfind() 的更多信息 read this link并制作脚本

关于javascript - 如何在运行 Mongodb 的 Mongoose 中执行脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59916614/

相关文章:

php - 使用 php 查询 MongoDB $IN

Javascript语法识别

javascript - IE8 数组和indexOf冲突

javascript - 为什么我的全局变量在 JSFiddle 上被覆盖了?

javascript - 是否可以在其他 then for() 循环中使用 await ?

Javascript/NodeJS : html rendering before . 在 forEach 内查找完成

node.js - 无法将 alpha 版本发布到 npm

python - 从 pymongo.objectid 导入 ObjectId 导入错误 : No module named objectid

javascript - 等到 Jquery 中的 await/async 返回

javascript - 使用 express 和 node.js 更新 mongodb 中的单个记录