0

I'm trying to query a collection with Mongoose, there is the collection sample output with a simple db.course.find() query

{
  "_id" : ObjectId("581c9408fc01b15cb21043e4"),
  "calendar_id" : DBRef("calendar", ObjectId("581c5972fd1c59295c34f1b8"), "ecampus"),
  "date" : 1478473200000,
  "title" : "Conception et planification BI",
  "teacher" : "fiolet gilles",
  "start_at" : "08:30",
  "end_at" : "12:30"
}

I have a MongoDB query that work well

db.course.find({'calendar_id.$id': ObjectId("581c5972fd1c59295c34f1b8")}).sort({date: 1})

I am trying to do the same query with Mongoose, in my NodeJS app I made this query but this one return an empty array because the ObjectId is not working well.

let mongoose = require('mongoose');
let ObjectId = mongoose.Types.ObjectId;
let id = new ObjectId(session.calendar_id);

Course.find({'calendar_id.$id': id}).sort({date: 1}).exec(function (err, courses) {
    console.log(err, courses);
    createJsonBody(courses);
});

Course is from my model file and is like this

const Course = mongoose.model('course', {
    calendar_id: Schema.ObjectId,
    date: Number,
    title: String,
    teacher: String,
    start_at: String,
    end_at: String
});

How can I make this Mongoose query to work ? The model is maybe not properly formed ?

1 Answer 1

1

Use Course.find({'calendar_id': id}) instead of Course.find({'calendar_id.$id': id}).

For mongoose $id does not exist.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks this is the perfect answer !
Also, you do not need to cast the id to ObjectId first, Mongoose does that for you implicitly behind the scenes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.