用户架构:
var mongoose = require("mongoose");
var passportlocalmongoose = require("passport-local-mongoose");
var userschema = new mongoose.Schema({
username:{
type:String,
unique:true,
required:true,
},
email:{
type:String,
unique:true,
require:true,
},
phonenumber:{
type:String,
required:true
},
password:{
type:String,
required:true
},
college:{
type:String,
required:true
},
papers : [
{
type:mongoose.Schema.Types.ObjectId,
ref:"Faper"
}
]
});
userschema.plugin(passportlocalmongoose);
module.exports = mongoose.model("User", userschema);
烟斗模式:
var mongoose = require("mongoose");
var faperschema = new mongoose.Schema({
department:{
type:String,
require:true
},
subject:{
type:String,
required:true
}
});
module.exports = mongoose.model("Faper",faperschema);
如何查询以获取具有给定“主题”的“用户”
这是我的代码的样子
app.get("/findfaper",function(req,res){
//stack overflow and mongoose doc comes to rescue
var college = req.query.college;
var subject = req.query.subject;
User.
find({college:college}).populate({
path: 'papers',
match: { subject: { $eq: subject }},
}).
exec(function(err,founddata){
if(err){
console.log("error in finding data");
}
else{
console.log(founddata);
res.render("fapers",{fapers:founddata});
}
});
});
(有时)返回空文件的“用户”
[ { papers: [],
_id: 5b5f2b278f0c621d3bb32f21,
username: 'hello',
college: 'Indian Institute of Technology Delhi',
email: 'sas@gmail.com',
phonenumber: 'sasa',
__v: 1 } ]
有时候我得到的用户没有给定的主题,这是因为
User.find({college:college})
部分。 那么我如何查询获得大学和论文的“用户”呢?