javascript - Mongoose 或 Query 不返回任何内容

标签 javascript node.js mongodb mongoose

我正在尝试查询具有适合给定用户时间表的学习类(class)的组。为什么以下查询不起作用?

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);

最佳答案

您必须执行查询才能“返回”某些内容。

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}}]}
]);

可以通过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);
}

或调用Query.prototype.then() (隐式执行查询):

// 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);
}

关于javascript - Mongoose 或 Query 不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56031798/

相关文章:

php - Ajax 返回值与 PHP 结合使用

javascript - 使用ajax在数据库中保存多个同名字段

javascript - Node JS 关闭读取流

node.js - Mongoose 中的自动递增序列

javascript - 通过一个操作 mongoDB/meteor 设置整个文档和特定值

php - Mongodb 和 PHP APC

javascript - 如何在具有特定文件扩展名的网页中查找所有链接?

javascript - 如何将 php 值传递给 script ,然后传递回 php ?

javascript - 使用 NodeJS 将开始和停止时间发布到 mysql(sequelize)

javascript - 从 Node 服务器访问js时出错