javascript - 模型未使用 mongoose 保存到 MongoDB

标签 javascript node.js mongodb mongoose readline

我正在尝试注册用户并将用户保存到 MongoDB。我正在使用 nodejs readline 模块创建用户。但是当我尝试将其保存到 mongodb 时它不起作用。它也不会返回任何错误

这是代码

const { Admin, validate } = require('../models/admin');
const mongoose = require('mongoose');
const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

const print_error = '\x1b[31m%s\x1b[0m'; 
const print_success = '\x1b[32m%s\x1b[0m'; 

function createUser() {
    rl.question('Please Enter Username : ', (username) => {
        rl.question('Please Enter a Password : ', async(password) => {
            const adminObject = {
                username,
                password
            };
            const { error } = validate(adminObject);
            if (error) {
                rl.close()
                rl.removeAllListeners()
                return console.log(print_error, error.details[0].message);
            }

            let admin = await new Admin({
                username: username,
                password: password
            });
            console.log(admin);
            const result = await admin.save(function(err,res){
                if(err){
                    console.log('err',err);
                    return console.log('err',err);
                }
                else return console.log('res', res);
            }); // save is not working
            console.log(print_success, result);
            rl.close(process.exit(1)); // close the process after done saving
        });
    });
}
createUser();

管理模型

const mongoose = require('mongoose');
const Joi = require('joi');

const Admin = new mongoose.model('Admin', new mongoose.Schema({
    username: {
        type: String,
        required: true,
        minlength: 1,
        maxlength: 10,
        unique: true
    },
    password: {
        type: String,
        required: true,
        minlength:3,
        maxlength: 1024
    }
}));

function validateAdmin(admin){
    const schema = {
        username: Joi.string().min(1).required(),
        password: Joi.string().min(3).required()
    };
    return Joi.validate(admin, schema);
}

exports.Admin = Admin;
exports.validate = validateAdmin;

P.S - 我已经连接到mongodb,连接成功。

最佳答案

I don't know why you're use async/await and then you use function in your save.

您可以使用以下代码更改您的 createUser 函数:

function createUser() {
    rl.question('Please Enter Username : ', (username) => {
        rl.question('Please Enter a Password : ', async(password) => {

            const { error } = validate({ username, password });

            if (error) {
                rl.close()
                rl.removeAllListeners()
                return console.log(print_error, error.details[0].message);
            }

            let admin = new Admin({username, password });

            try {
              const result = await admin.save(); 
              console.log(print_success, result);
              rl.close(process.exit(1)); 
            } catch(ex) {
              console.log(ex.message);
            }
        });
    });
}

If you've any problem, then let me know in the comment below.

更新:测试代码后,createUser.js 中没有连接。

我已在您的 createUser() 上方添加了此连接,并且它正在工作:

mongoose.connect('mongodb://localhost:27017/url-shortener');

Please, make sure you've add a connection to your mongodb.

希望对你有帮助。

关于javascript - 模型未使用 mongoose 保存到 MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60126065/

相关文章:

json - 如何更新json文件中的值并通过node.js保存

mongodb - 如何使用 insert_many 方法处理 pymongo AutoReconnect 异常

Javascript对象属性数组,无法访问值

javascript - 如何在 Microsoft Edge 的 html5 中用逗号代替点作为输入数字的小数点

javascript - jquery 按日期对非必填字段进行验证

javascript - 如何在部署expressjs应用程序时修复heroku错误?

javascript - 使用等待时请求 promise 抛出意外的标识符错误

mongodb - pymongo 无法连接到远程服务器上的数据库

java - 从 Java 使用 mongodb

javascript - 处理JavaScript中Firebase身份验证错误的有效方法