【发布时间】:2021-06-17 21:36:09
【问题描述】:
我正在尝试返回与查询字段匹配的子文档。我只想返回与用户匹配的 PIN,该 PIN 保存在帐户集合中。这就是我目前所得到的。
router.post('/SelectUser', async(req, res) =>{
try{
const acc = await Account.findOne({"Email": req.body.Email});
if(!acc) throw Error('Email not found');
var user = await Account.findOne({"Users.Username":req.body.User.Username},{Users:{PIN:1}});
}
这会输出与帐户关联的所有 PIN,这不是我想要的。以下是我正在使用的模式和模型:
帐号:
const User = require('../Models/UserData');
const AccountSchema = new Schema({
// Email linked to this account
Email:{
type:String,
unique:true,
required:true,
index:true
},
// Password for the account
Password:{
type : String,
required : true
},
// Users on this account
Users:{
type:[User],
required:true
}
});
module.exports = mongoose.model('Account', AccountSchema);
用户:
const UserSchema = new Schema({
// Name of the user
Username:{
type:String,
required:true,
unique:true
},
// PIN for each user
PIN:{
type:Number,
require:true
}
});
module.exports = UserSchema;
【问题讨论】:
-
使用您当前的架构,无法将电子邮件与单个用户相关联,因此无法判断您尝试获取关联 PIN 的“用户”。
-
@CodyHaines 您将如何更改它们以使其成为可能?
标签: node.js arrays mongodb mongoose