简体   繁体   中英

Mongoose or Query does not return anything

I am trying to query groups that have study sessions that fit a given users schedule. Why does the following query not work?

Group.find().or([
  {$and: [ {mondayStart: {lte: 6}}, {mondayEnd:  {gte: 8}}] },
  {$and: [ {tuesdayStart: {lte: 9}}, {tuesdayEnd: {gte:13}}] },
  {$and: [ {wednesdayStart: {lte: 9}}, {wednesdayEnd: {gte: 12}}]
])


const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const GroupSchema = new Schema({
  owner: {type: mongoose.Schema.ObjectId, ref: 'users'},
  subject: String,
  date: {type: Date, default: Date.now},
  mondayStart: Number,
  mondayEnd: Number,
  tuesdayStart: Number,
  tuesdayEnd: Number,
  wednesdayStart: Number,
  wednesdayEnd: Number
});

module.exports = Group = mongoose.model('groups', GroupSchema);

You have to execute the query for it to "return" something.

const query = Group.find().or([
    {$and: [{mondayStart: {lte: 6}}, {mondayEnd: {gte: 8}}]},
    {$and: [{tuesdayStart: {lte: 9}}, {tuesdayEnd: {gte: 13}}]},
    {$and: [{wednesdayStart: {lte: 9}}, {wednesdayEnd: {gte: 12}}]}
]);

A Query can be executed via Query.prototype.exec() :

// Using a callback
query.exec((err, groups) => {
    if (err) console.error(err);
    else console.log(groups);
});

// As a promise
query.exec().then((groups) => {
    console.log(groups);
}).catch((err) => {
    console.error(err);
});

// As a promise using async/await
try {
    const groups = await query.exec();
    console.log(groups);
} catch (err) {
    console.error(err);
}

Or by calling Query.prototype.then() (which implicitly executes the query):

// Using then
query.then((groups) => {
    console.log(groups);
}).catch((err) => {
    console.error(err);
});

// Using async/await
try {
    const groups = await query;
    console.log(groups);
} catch (err) {
    console.error(err);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM