美文网首页
mongoose在定义schema的小技巧

mongoose在定义schema的小技巧

作者: wivwiv | 来源:发表于2017-09-23 00:29 被阅读486次

这些技巧还是很有帮助的,主要是对Schema的Options总结

各种建模的项目地址: 简单的商城

1. 指定collections名字 [ 指定表名 ]

mongoose默认的集合名字是model的复数形式,比如定义如下:

module.exports = mongoose.model('Admin', AdminSchema)  // model名字是Admin

MongoDB 中查看集合:

show collections
> admins

事实上如果我们需要在mongoose中指定集合名字的话,定义 Schema时可以为其加上一个配置项:

// 定义集合名字: collection: string
new mongoose.Schema({
    username: { type: String, required: true, index: true, display: '用户名' },
  },
  {
    collection: 'admin',
  })

再次执行后,使用客户端mongod进入MongoDB查看集合验证吧!

2.指定生成createAt & updateAt字段
new mongoose.Schema({
    username: { type: String, required: true, index: true, display: '用户名' }
  },
  {
    collection: 'admin',
    versionKey: false,
    // timestamps: true 
    timestamps: {
      createdAt: true,
      updatedAt: true,
    },
  })

这样你在插入和更新时mongoose就会自动创建createdAt, updatedAt字段同时插入相关时间,

推荐博文 [ 网上看到写的不错的 ]:

http://blog.csdn.net/weixin_36743929/article/details/54883146

相关文章

网友评论

      本文标题:mongoose在定义schema的小技巧

      本文链接:https://www.haomeiwen.com/subject/pheqextx.html