大家好,我对此有争议。我在mlab上有2个集合,但是它们是同一个数据库。所以我的问题是我的代码只保存1个集合。这里可能是什么问题。
型号/user.js
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
//User Schema
//authToken and isAuthenticated is for UserSchema of email-verification
var UserSchema = mongoose.Schema({
username:{
type: String,
unique: true,
index:true
},
password:{
type:String
},
email:{
type:String,
required: true
// unique: true
},
authToken:{
type: String,
required: true,
unique: true
},
IsAuthenticated:{
type: Boolean,
required: true
},
name:{
type:String
},
field:{
type:String
},
e_money:{
type:Number //this is the integer form in mongoose
}
});
//accesible variable from the outside
var User = module.exports = mongoose.model('User', UserSchema);
//create the user
module.exports.createUser= function(newUser, callback){
bcrypt.genSalt(10, function(err,salt){
bcrypt.hash(newUser.password, salt, function(err, hash){
//store hash in your password DB
newUser.password = hash;
newUser.save(callback);
});
});
}
模型/ infouser.js
var mongoose = require('mongoose');
//User Schema
var UserSchema = mongoose.Schema({
username:{
type: String,
unique: true,
index:true
},
name:{
type:String
},
field:{
type:String
},
e_money:{
type:Number //this is the integer form in mongoose
}
});
//accesible variable from the outside
var InfoUser = module.exports = mongoose.model('infouser', UserSchema);
//create the user
module.exports.createUser= function(newUser, callback){
newUser.save(callback);
}
这就是我在route / users.js上称呼它们的方式
var User = require('../models/user');
var InfoUser = require('../models/infouser');
var newUser = new User({
name: name,
email: email,
authToken: authToken,
IsAuthenticated: false,
username: username,
password: password,
field: field,
e_money: e_money //temporary emoney
});
var newUser2 = new InfoUser({
name: name,
username:username,
field:field,
e_money:e_money
});
InfoUser.createUser(newUser2,function(err,user){
if(err) throw err;
console.log(user);
});
//save the newly created user to database
User.createUser(newUser,function(err, user){
if(err) throw err;
console.log(user);
}
这两个数据仅保存在我的用户集合中。我在这里想要的是将infouser数据保存在我的infouser集合中,并将我的users集合保存在我的users集合中
最佳答案
嗯,模型上的creteUser函数真的很奇怪,因为您可以在那里传递任何模型的实例,它将调用自己的保存函数。
为什么不直接调用save函数呢? (也许您可以用它消除范围界定问题):
类似于(带有承诺)的东西:
var User = require('../models/user');
var InfoUser = require('../models/infouser');
var newUser = new User({
name: name,
email: email,
authToken: authToken,
IsAuthenticated: false,
username: username,
password: password,
field: field,
e_money: e_money //temporary emoney
});
var newUser2 = new InfoUser({
name: name,
username:username,
field:field,
e_money:e_money
});
newUser.save()
.then(function(user) {
console.log(user);
})
.catch(function(e) {
console.log(e);
});
newUser2.save()
.then(function(user) {
console.log(user);
})
.catch(function(e) {
console.log(e);
});
关于javascript - Mongoose 中的多个module.export,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45026275/