You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过命令行向MongoDB插入新数据对象?Node.js代码改造求助

实现命令行参数添加MongoDB数据的方案

要实现通过命令行传入姓名和号码来添加新联系人,你可以通过判断process.argv的参数长度,区分执行查询列表和添加数据两种逻辑,以下是修改后的完整代码:

const mongoose = require('mongoose')

// 参数合法性校验
if (process.argv.length < 3) {
  console.log('请按格式输入参数:\n- 查询列表:node mongo.js <密码>\n- 添加联系人:node mongo.js <密码> <姓名> <号码>')
  process.exit(1)
}

const password = process.argv[2]
// 替换URL中的硬编码密码为传入的参数(原代码此处存在硬编码错误,必须修正)
const url =
  `mongodb+srv://username:${password}@phonebook.axquldz.mongodb.net/personsApp?retryWrites=true&w=majority`

mongoose.set('strictQuery', false)
mongoose.connect(url)

const personSchema = new mongoose.Schema({
  name: String,
  number: Number,
})

const Persons = mongoose.model('Person', personSchema)

// 判断是否传入了姓名和号码参数
if (process.argv.length === 5) {
  const name = process.argv[3]
  // 将命令行传入的字符串号码转为数字类型,匹配Schema定义
  const number = Number(process.argv[4])

  const person = new Persons({
    name,
    number
  })

  person.save().then(() => {
    console.log(`已成功保存联系人:${name} ${number}`)
    mongoose.connection.close()
  })
} else {
  // 参数长度为3时,执行联系人列表查询
  Persons.find({}).then(result => {
    console.log('当前联系人列表:')
    result.forEach(person => {
      console.log(`${person.name} ${person.number}`) 
    })
    mongoose.connection.close()
  })
}

关键改动说明

  • 参数分支逻辑:通过process.argv.length判断操作类型:
    • 长度为3时(仅传入密码):执行原有查询逻辑,输出所有联系人
    • 长度为5时(传入密码、姓名、号码):执行添加数据逻辑
  • 修复数据库连接问题:原代码URL中的密码是硬编码字符串,替换为传入的password变量,否则无法正常连接数据库
  • 数据类型适配:命令行参数默认是字符串,通过Number()将号码转为数字类型,匹配Schema中定义的number字段类型
  • 提示信息优化:参数错误时给出清晰的格式提示,方便用户正确使用

内容的提问来源于stack exchange,提问作者Jabri Juhinin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 22:35:08