以下划线为前缀的属性的 eslint 问题

Moh*_*sal 3 mongoose node.js eslint

我是 NodeJS 和 MongoDB 的初学者,在从一些在线资源中学习的同时,我创建了 mongoose 模式:

const mongoose = require('mongoose')

const blogSchema = mongoose.Schema({
  title: String,
  author: String,
  url: String,
  likes: Number,
})

blogSchema.set('toJSON', {
  transform: (document, returnedObject) => {
    returnedObject.id = returnedObject._id.toString()
    delete returnedObject._id
    delete returnedObject.__v
  }
})

Run Code Online (Sandbox Code Playgroud)

但是 eslint 不断给我错误:

  1. for returnedObject.id, delete returnedObject._idand delete returnedObject.__v- 分配给函数参数 'returnedObject'.eslint(no-param-reassign) 的属性
  2. for returnedObject._idand returnedObject.__v- '_id'.eslint(no-underscore-dangle) 中意外的悬空 '_'

eslint 错误的快照

我可以删除_id__v字段并重新分配_ididfor的正确方法是什么returnedObject

我正在使用基于 airbnb 的 eslint 配置(devDependencies来自package.json):

    "eslint": "^6.8.0",
    "eslint-config-airbnb-base": "^14.0.0",
    "eslint-plugin-import": "^2.20.1",
Run Code Online (Sandbox Code Playgroud)

Moh*_*sal 5

正如@CherryDT 和@slebetman 在上述评论中所建议的那样 -代码没有任何问题,问题仅与 eslint 配置有关

我想出了以下解决方案:

禁用线路

在您看到此错误的行上方添加注释:

// eslint-disable-next-line no-param-reassign, no-underscore-dangle
returnedObject.id = returnedObject._id.toString()
Run Code Online (Sandbox Code Playgroud)

或在该行旁边:

returnedObject.id = returnedObject._id.toString() // eslint-disable-line no-param-reassign, no-underscore-dangle
Run Code Online (Sandbox Code Playgroud)

禁用文件

在文件的第一行添加注释:

/* eslint-disable no-param-reassign, no-underscore-dangle */
Run Code Online (Sandbox Code Playgroud)

关闭 eslint 配置中的规则(通常是.eslintrc.js.eslintrc.yml或者类似 name 的东西.eslintrc.*

rules: {
  no-underscore-dangle: off,
  no-param-reassign: off,
}
Run Code Online (Sandbox Code Playgroud)

上面的示例如果对于yml配置,可以使用其他配置完成类似的操作。

前两个解决方案不太适合庞大的代码库,因此我建议使用第三个选项。

*可以在同一个注释中关闭多个错误,用逗号分隔。