Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mongodb折腾记 #24

Open
Ray-56 opened this issue Jul 3, 2020 · 0 comments
Open

mongodb折腾记 #24

Ray-56 opened this issue Jul 3, 2020 · 0 comments
Labels

Comments

@Ray-56
Copy link
Owner

Ray-56 commented Jul 3, 2020

mongodb折腾记

最近在写一个由node koa2 mongodb创建的一个后台接口服务的这么一个项目, 可能会遇到各式各样的问题, 故而以此来记录.

mongoose创建collection时自动加入s

在对dbCURD时这里使用mongoose. 集成了一些方法, 调用起来方便快捷.
使用collection时一般会这样调用, model中:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const userSchema = ({
    name: String,
    password: String
});

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

User添加一些数据后

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const userSchema = ({
    name: String,
    password: String
});

const userController = mongoose.model('User', userSchema);

// 添加数据
const res = new userController({ name: 'admin', password: '123456'}).save();

执行成功后在数据库中查看

> user 你的数据库名
> show collections
users

只能查看到有users这个文档, 而不是想象中的user.

这里的问题出在创建model时, 在mongoose.model()这里可以传入三个参数

  1. modelName: 模型的集合名.
  2. Schema: 结构对象, 定义类型/默认值/验证/索引等.
  3. collectionName: collection的名称, 不传时默认取model的第一个参数加s.

到这里也就分析出症结所在, 只需要再加入一个参数即可.

@Ray-56 Ray-56 added the Node label Jul 3, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant