我有2个文件a"用户文件"和#34; UserToken文档"。这应该像一对多的关系。
user.model.js
var UserSchema = new Schema({
username: {
type: String,
unique: true,
required: true
},
email: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
active: {
type: Boolean,
default: false,
},
tokens: [{
type: Schema.ObjectId,
ref: 'UserToken'
}],
});
module.exports = mongoose.model('User', UserSchema);
usertoken.model.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserTokenSchema = new Schema({
type: {
type: String
},
token: {
type: String
},
expiry: {
type: Date,
default: null
},
user: [{
type: Schema.ObjectId,
ref: 'User'
}]
});
module.exports = mongoose.model('UserToken', UserTokenSchema);
user.controller
var user = new User({
username: input.username,
email: input.email,
password: input.password,
active: false
});
user.save(function(err) {
var userToken = new UserToken({
type: 'new',
token: token,
expiry: null,
user: user._id
userToken.save(function(err) {
})
})
当我显示用户时,它应该填充/检索与该用户关联的所有令牌。目前它没有这样做。
查询
User.find({})
.populate('tokens')
.exec(function(err, users) {
if(err) return res.json({success: 'false', errors: err});
return res.json(users);
});
数据
[
{
username: "TestUser",
email: "TestEmail@hotmail.com",
password: "$2a$10$I4wJ.e3eVK7EMcfdf46x0e5kYnSTzHPTcBmzXIctduM./pZEiGbPG",
_id: "56ab4bbfa8f3e11813803566",
__v: 0,
tokens: [ ],
active: false
}
]
然而,当我显示令牌时,它正在检索关联的用户。
查询
UserToken.find({})
.populate('user')
.exec(function(err, tokens) {
if(err) return res.json({success: 'false', errors: err});
return res.json(tokens);
});
数据
[
{
type: "new",
token: "16c72da8-78a7-4ee1-9b03-f5e490d7e010",
_id: "56ab4bbfa8f3e11813803567",
__v: 0,
user: [
{
username: "TestUser",
email: "TestEmail@hotmail.com",
password: "$2a$10$I4wJ.e3eVK7EMcfdf46x0e5kYnSTzHPTcBmzXIctduM./pZEiGbPG",
_id: "56ab4bbfa8f3e11813803566",
__v: 0,
tokens: [ ],
active: false
}
],
expiry: null
}
]
如何使用所有关联的令牌检索用户?
答案 0 :(得分:0)
这应该像是一对多的关系。
感觉您在解决方案中正在建模 N 到 N 关系:
var UserSchema = new Schema({
tokens: [{
type: Schema.ObjectId,
ref: 'UserToken'
}]
...
var UserTokenSchema = new Schema({
user: [{
type: Schema.ObjectId,
ref: 'User'
}]
...
除此之外,您如何在数据库中插入数据?请记住,没有框架可以理解关系,您必须手动完成(每次创建新文档时更新引用)例如
var u1 = { ... }
Users.create(u1, function(err, user) {
UserTokens.findAndUpdate(userTokenId, {user: user._id}, function(err, uToken){
// now userToken has the reference to your new user (u1)
})
})