跳转至

踩坑 mongoose

1 mongoose 创建的 collection 名带后缀 s?

可能代码如下:

const schema = new mongoose.Schema({
  username: {
    type: String
  },
  password: {
    type: String
  }
})
mongoose.model('User', schema)

原因:这个问题是因为没有给 collection 指定名称,而导致系统默认使用 modle 名称按一定规则产生(modle 小写 +s)

解决方法如下:

//方法1
let collectionName = 'User'
let M = mongoose.model('User', schema, collectionName);
//方法2
schema.set('collection','User')
//方法3
const schema = new mongoose.Schema({
  username: {
    type: String
  },
  password: {
    type: String
  }
}{collection:'User'})

友情提示: 如果查到不到数据,而数据确实存在,原因也可能是这个。代码调用的 collection 和数据库中的不一样