我需要在我的getHistory模块中找到 person1 deals..so的历史记录我已经过滤了 person1的 dealSchema中的所有交易,在 acceptreject < / strong> function我使用聚合概念来过滤在接受的字段中具有 person1的 _d的交易。但是回调函数acceptreject没有获取它总是导致[]的结果..任何人都可以找到我在这段代码中所犯的错误。提前谢谢
var acceptreject = function (userId, callback){//callback function for finding accepted deal
console.log("Aggregate:" +userId);
if(userId == null && userId == 'undefined'){
console.log("error fetching id");
res.send(new Response.respondWithData('failed','Invalid userId'));
return next();
}
User.aggregate([
{
$unwind: "$deals"
},
{
"$match":
{
"deals.accepted": userId
//"deals.rejected": id
}
},
{
$project:{
"shopName":"$deals.shopName",
"deal":"$deals.deal",
"price":"$deals.price",
"name":"$name"
}
}
],function (err, user){
console.log(user);
if (err){
callback (err);
}
console.log("Your accepted deal:"+ user);
// res.send(200,user);
callback(null, user);
})
}
exports.getHistory = function (req, res, next) {
var incomingUser = req.user;
var id = incomingUser._id;
User.findById(id,function (err, user){
console.log(user);
if (err) {
return next(new Response.respondWithData('failed','Cant find theuser'));
}
var dealObj = _.filter(user.deals);
acceptreject({
userId : id
},function(err, users){
if(err){
res.send(new restify.InternaError(err.message));
return next();
}
else{
console.log("final");
var final = {
accepteddeal: users,//it returns [] in result but person1 accepted the deal
mydeal: dealObj
}
next(res.send(200, final));
}
});
});
}
我的架构是
var dealSchema = new mongoose.Schema({
shopName: {type: String,required: true},
deal: {type: String,required: true},
price:{type: Number,required: true},
start:{type: Date,default: Date.now},
end:{type: Date},
expiry:{type: Date},
comments:{type: String},
accepted: {type:mongoose.Schema.Types.ObjectId, ref:'user'},//person1 _id
rejected: {type:mongoose.Schema.Types.ObjectId, ref: 'user'}
});
var userSchema = new mongoose.Schema({
name: { type: String,required: true},
phone: { type: Number, required: true,unique: true},
email:{type: String},
password: {type: String},
deals:[dealSchema]
}, {collection: 'user'});
mongoose.model('Deal', dealSchema);
mongoose.model('user', userSchema);
答案 0 :(得分:0)
我在回调函数中犯了一个错误,其中该函数的userId参数未传递id
var accept= function (userId, callback){
console.log("Aggregate:" +userId);
if(userId == null && userId == 'undefined'){
res.send(new Response.respondWithData('failed','Invalid userId'));
return next();
}
var id = new Object(userId);
console.log(id);
User.aggregate([
{
$unwind: "$deals"
},
{
"$match": {
"deals.accepted" : id
}
},
{
$project:{
"shopName":"$deals.shopName",
"deal":"$deals.deal",
"price":"$deals.price",
"name":"$name"
}
}
],function (err, user){
console.log(user);
if (err){
callback(err);
}
console.log("Your accepted deal:"+ user);
//res.send(200,user);
callback(null, user);
})
}