我正在尝试通过 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()
});
}
了解有关 mongooes
中 find()
的更多信息 read this link并制作脚本
关于javascript - 如何在运行 Mongodb 的 Mongoose 中执行脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59916614/