无法使用save方法在mongo db中保存数据

时间:2018-06-16 17:20:52

标签: mongodb

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;
db.on('error',console.error.bind(console,'connection error:'));

var UserSchema = mongoose.Schema({
    username:{
        type:String,
        index:true
    },
    password:{
        type:String
    },
    email:{
        type:String
    },
    name:{
        type:String
    }
});

var User  = mongoose.model('User',UserSchema);
//code getting used to save data
// Accessing this code from user.js file , new user is getting printed                  
//but data is not getting saved in db.  
var createUser = function(newUser,callback){
    console.log(newUser);
    newUser.save(callback);
};

module.exports = {
    User,
    createUser
};

1 个答案:

答案 0 :(得分:0)

尝试此步骤: 1.只需导出用户 2.要求用户调用保存功能; 3.尝试调用此代码:

var newUser = new User({})
newUser.email = 'simon@theholmesoffice.com',
newUser.username='replace with username',
newUser.password ='replace with password',
newUser.name='replace with name'
newUser.save( function( err, user ){
if(!err){
console.log('_id of saved user: ' + user._id);
}
});