假设您知道如何设置猫鼬并连接您的数据库并且只需要正确的查询,让我与您提供的模型分享我注意到的一些东西。我认为不需要 2 个集合,因为您可以将相同的东西存储在一个集合下,因为它节省了从信息模式查找用户数据的时间。所以用户模式可以是
var usersSchema = mongoose.Schema({
user_id: String,
username: String,
password: String,
khatam_id: String,
fullname: String
});
使用以下查询可以获取用户详细信息
Users.findOne({})
.then(function(user){
// do something
})
.catch(function(err){
// handle error
})
与使用聚合查询或猫鼬填充函数相比,这更高效、更快捷。
如果上述方法不适合你,你可以试试猫鼬填充功能。
UserSchema = new mongoose.Schema({
user_id: String,
password: String,
},
// schema options: Don't forget this option
// if you declare foreign keys for this schema afterwards.
{
toObject: {virtuals:true},
// use if your results might be retrieved as JSON
// see http://stackoverflow.com/q/13133911/488666
//toJSON: {virtuals:true}
});
UserInfoSchema = new mongoose.Schema({
user_id: String,
khatam_id: String,
username: String,
fullname: String,
});
// Foreign keys definitions
UserSchema.virtual('userDetails', {
ref: 'UserInfoSchema',
localField: 'user_id',
foreignField: 'user_id',
justOne: true // for many-to-1 relationships
});
// Models creation
var UserSchema = mongoose.model('UserSchema', UserSchema);
var UserInfoSchema = mongoose.model('UserInfoSchema', UserInfoSchema);
// Querying
UserSchema.find({...})
// if you use select() be sure to include the foreign key field !
.select({.... user_id ....})
// use the 'virtual population' name
.populate('userDetails')
.exec(function(err, books) {...})