簡體   English   中英

使用mongoDB的Node Js Cli

[英]Node Js Cli with mongoDB

因此,我創建了一個Commander.js命令,該命令創建了一個帳戶,但是我沒有得到任何關於錯誤甚至成功的反饋。

這是文件

 #!/usr/bin/env node

const program = require('commander');
const userModel = require('../mongo/userModel');
const bcryptjs = require('bcryptjs');

program
  .version('0.0.1')
  .description('Contact management system');

program
  .command('createadminaccount <name> <username> <email> <password>')
  .alias('c')
  .description('Add a admin account')
  .action((name, username, email,password) => {

    userModel.findOne({email: email}, function (err, existingUser) {
      if (err) return console.log("Error");
      if (existingUser) {
        return console.log('Email is already registered');
      }

      let newUser = new userModel({
        name: req.body.name,
        username: req.body.username,
        email:req.body.email,
        password: req.body.password,
        staffMember: true,
        verified: true
      })

      bcryptjs.genSalt(10, function (err, salt) {
        bcryptjs.hash(newUser.password, salt, (err, hash) => {
          if (err) return console.log("Error");
          newUser.password = hash;
          newUser.save();

          console.log('Registered Successfully')
        })
      })
    })
  });

program.parse(process.argv);

這是userModel文件:

const mongoose = require('mongoose');

const UserSchema = mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  username: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    required: true
  },
  verified: {
    type: Boolean,
    default: false
  },
  date: {
    type: Date,
    default: Date.now
  },
  staffMember: {
    type: Boolean,
    default: false
  }
})

const User = module.exports = mongoose.model('User', UserSchema);

我沒有收到任何消息,也沒有代碼在數據庫中創建帳戶,即使我使用相同的方法在API方法中創建帳戶,也只是代碼無法繼續執行,例如,如果我刪除了bcryptjs import,我將沒有任何錯誤

首先,不要在bash文件.command('createadminaccount ...')調用命令名稱,而是在package.json的名稱中這樣命名

  "name": "createadminaccount",

那么您需要在bin中定義您要調用的文件的名稱(我假設它的名稱為admincommander.js,並且位於package.json文件的同一文件夾中),還需要將preferred global定義為true,在package.json

  "preferGlobal": true,
  "bin": "./admincommander.js"

在此運行npm link以鏈接文件后(您也可以稍后再運行npm unlink來取消鏈接文件)

然后最終運行createadminaccount ,魔術就會發生

我希望我有所幫助:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM