简体   繁体   English

模型不使用猫鼬保存到 MongoDB

[英]Model not saving to MongoDB using mongoose

I am trying to register a user and save the user to MongoDB.我正在尝试注册用户并将用户保存到 MongoDB。 I am creating the user using nodejs readline module.我正在使用 nodejs readline模块创建用户。 But when I am trying to save it to the mongodb it is not working.但是当我试图将它保存到 mongodb 时它不起作用。 Nor does it is returning any error .它也不会返回任何error

Here's the code这是代码

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

Admin Model管理模式

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;

PS - I've connected to the mongodb, the connection is successful. PS - 我已经连接到mongodb,连接成功。

I don't know why you're use async/await and then you use function in your save .我不知道你为什么使用async/await然后在你的save使用function

You can change your createUser function with this code below:您可以使用以下代码更改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.如果您有任何问题,请在下面的评论中告诉我。

Updated: After test your code, you have no connection in your createUser.js .更新:测试您的代码后,您的createUser.js没有连接。

I've been add this connection below in above of your createUser() and it's working:我已经在下面的createUser()上面添加了这个连接并且它正在工作:

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

Please, make sure you've add a connection to your mongodb .请确保您已添加到mongodb的连接。

I hope it can help you.我希望它能帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM