Reputation: 1
I have a schema like this
var DateOnly = require('mongoose-dateonly')(mongoose);
const HealthSchema = new Schema({
temprature: {
type: Number,
default: 0,
},
date: {
type:DateOnly,
default: Date.now,
},
});
const PredictionSchema= new mongoose.Schema({
healtData: [HealthSchema]
});
module.exports = Prediction = mongoose.model("Prediction", PredictionSchema);
I am creating referance id for this schema in userSchema
const UserSchema = new Schema({
predictionId:{
type: mongoose.Types.ObjectId,
ref: "Prediction",
}
})
My question is, for this given schema I want to fetch temperature for given date and given user.I am giving referance id to PredictionSchema for all users.How can i do so?
Upvotes: 0
Views: 54
Reputation: 36104
$match
you user id condition$lookup
with prediction collection and pass prediction id in let
,$match
prediction id condition and date conditionlet userId = 1; // convert to object id using mongoose.Types.ObjectId(userId)
let date = new Date("2020-12-01");
let startDate = new Date(new Date(date).setUTCHours(00,00,00,000));
let endDate = new Date(new Date(date).setUTCHours(23,59,59,999));
User.aggregate([
{ $match: { _id: userId } },
{
$lookup: {
from: "predictions",
let: { predictionId: "$predictionId" },
pipeline: [
{
$match: {
$expr: { $eq: ["$_id", "$$predictionId"] },
"healtData.date": {
$gte: startDate,
$lte: endDate
}
}
}
],
as: "Prediction"
}
}
])
Upvotes: 1