gpt4 book ai didi

javascript - Mongoose 保存到 2 集合

转载 作者:行者123 更新时间:2023-11-30 15:11:52 24 4
gpt4 key购买 nike

大家好,我真的需要帮助。困扰了我多少天

model/user.js

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('users', UserSchema);

var InfoUser = module.exports = mongoose.model('infouser', UserSchema);

我是这样保存的

var User = require('../models/user);

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,
email: email,
authToken: authToken,
IsAuthenticated: false,
username: username,
password: password,
field: field,
e_money: e_money //temporary emoney

});




//save the newly created user to database
User.createUser(newUser,function(err, user){
if(err) throw err;
console.log(user);
)};

User.createUser(newUser2,function(err,user){
if(err) throw err;
console.log(user);
)};

它总是说未定义信息用户是什么问题。有人可以吗

最佳答案

问题是您正在通过相同的 module.exports 导出两个不同的模型。相反,我建议您单独导出它们:

model/user.js

// You can add instance methods like this:
UserSchema.methods.createUser = function(user) {
// Whatever you want to do here
};

var User = mongoose.model('users', UserSchema);
var InfoUser = mongoose.model('infouser', UserSchema);

exports.User = User;
exports.InfoUser = InfoUser;

/*
You could also do this as:
module.exports = { User: User, InfoUser: InfoUser };
*/

然后当你想使用它们时:

var User = require('../models/user').User;
var InfoUser = require('../models/user').InfoUser;

关于javascript - Mongoose 保存到 2 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45018487/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com