Mongoose插入没有属性的文档

时间:2017-06-07 04:42:02

标签: node.js mongoose

MongoDB插入没有属性的文档(查看帖子的底部以查看我的集合的样子)。当我尝试插入以下内容时,我正在使用邮递员测试我的数据库:

{
    "username":"JohnDoe",
    "password" : "123456"   
}

我正在构建一个MEAN堆栈应用程序。另外,我注意到如果我将属性设置为必需,postman告诉我它无法注册用户。这就是为什么我评论它,但即使没有它并得到积极的回应我仍然得到我的收藏中的空文件。

邮差告诉我:

{
  "success": true,
  "msg": "User registered"
}

我的user.js文件

 const bcrypt = require ('bcryptjs');
    const config = require ('../config/database');

    //UserSchema

    const UserSchema = mongoose.Schema({            
        username: {
            type: String,
            //required: true
        },
        password: {
            type: String,
            //required: true
        }

    });

    const User = module.exports = mongoose.model("User", UserSchema);

    //To user function outside
    module.exports.getUserById = function(id, callback){
        User.findById(id,callback);
    }

    module.exports.getUserByUsername= function(username, callback){
        const query = {username: username}
        User.findOne (query,callback);
    }

    User.addUser = function (newUser, callback) {
        bcrypt.genSalt(10, (err, salt) =>{
            bcrypt.hash(newUser.password, salt, (err, hash) => {

                newUser.password = hash;
                newUser.save(callback);
            });
        });
    }

我的users.js文件:

const express = require('express');
const router = express.Router();
const passport = require('passport');
const jwt = require('jsonwebtoken');
const User = require('../modules/user');

// Register
router.post('/register', (req, res, next) => {
  let newUser = new User({
    username: req.body.username,
    password: req.body.password
  });

  User.addUser(newUser, (err, user) => {
    if(err){
      res.json({success: false, msg:'Failed to register user'});
    } else {
      res.json({success: true, msg:'User registered'});
    }
  });
});    

module.exports = router;

我在收藏中看到的内容:

{
    "_id": {
        "$oid": "5937b36bafdd733088cb27d0"
    },
    "__v": 0
}

1 个答案:

答案 0 :(得分:0)

你应该了解什么是mongoose statics and methods

在用户模型中,你应该根据你想要的方式将函数声明为方法和静态。

private void displayClients()
    {
        Intent intent = getIntent();
        boolean shouldRefreshData = intent.getBooleanExtra(IntentKeysKt.getShouldRefreshData(),false);
        Toast.makeText(this, "shouldRefreshData="+shouldRefreshData, Toast.LENGTH_SHORT).show();
        if (shouldRefreshData) {
            //Load data from clients table
            intent.putExtra(IntentKeysKt.getShouldRefreshData(), false);
            ClientsRetrievalTask clientsRetrievalTask = new ClientsRetrievalTask(this);
            clientsRetrievalTask.execute(agentGUID);
        }
    }

@Override
    public void clientsRetrieved(@NotNull List<Client> clients) {
        clientsAdapter.refresh(new ArrayList<>(clients));
        recyclerViewClients.setVisibility(View.VISIBLE);
        frameLayoutPlaceholderFragment.setVisibility(View.INVISIBLE);
    } 

在您的控制器用户文件中,您应该将addUser与您导出的模型上的用户模型实例一起使用。检查以下..

const bcrypt = require ('bcryptjs');
const config = require ('../config/database');

//UserSchema

const UserSchema = mongoose.Schema({            
    username: {
        type: String,
        //required: true
    },
    password: {
        type: String,
        //required: true
    }

});


//To user function outside
UserSchema.statics.getUserById = function(id, callback){
    User.findById(id,callback);
}

UserSchema.statics.getUserByUsername= function(username, callback){
    const query = {username: username}
    User.findOne (query,callback);
}

UserSchema.methods.addUser = function (callback) {
    bcrypt.genSalt(10, (err, salt) =>{
        bcrypt.hash(newUser.password, salt, (err, hash) => {

            this.password = hash;
            this.save(callback);
        });
    });
}

exports.User = mongoose.model("User", UserSchema);