mongodb find正在获取mongoose中子文档的空数组

js5cn81o  于 2023-03-07  发布在  Go
关注(0)|答案(1)|浏览(148)

有人能帮帮我吗?我试图获取在toDoEmail中包含匹配电子邮件的对象,但是find方法返回空数组,尽管我有匹配电子邮件的对象。
下面是我的模型:

const mongoose = require("mongoose");
const schema = mongoose.Schema;

const title = new schema({
  title: {
    type: String,
    trim: true,
    required: [true, "Title is required to create a ToDo"],
  },
  createdAt: { type: String, trim: true, default: new Date() },
  updatedAt: { type: String, trim: true, default: new Date() },
});

const email = new schema({
  email: {
    type: String,
    trim: true,
    required: [true, "email is required to create a ToDo"],
  },
  createdAt: { type: String, trim: true, default: new Date() },
  updatedAt: { type: String, trim: true, default: new Date() },
});

const tasks = new schema({
  tasks: [
    {
      task: {
        type: String,
        trim: true,
        required: [true, "Atleast one task is required to create a ToDo"],
      },
      status: { type: Boolean, trim: true, default: false },
      createdAt: { type: String, trim: true, default: new Date() },
      updatedAt: { type: String, trim: true, default: new Date() },
    },
  ],
});

const status = new schema({
  status: { type: Boolean, trim: true, default: false },
  createdAt: { type: String, trim: true, default: new Date() },
  updatedAt: { type: String, trim: true, default: new Date() },
});

const toDoSchema = new schema(
  {
    toDoTitle: title,
    toDoTasks: tasks,
    toDoStatus: status,
    toDoEmail: email,
  },
  {
    timestamps: true,
  }
);

const toDoModel = mongoose.model("toDo", toDoSchema);
module.exports = toDoModel;

这是我路线:

router.get("/fetchalltodos/:email", fetchAllToDos);

这是我的控制器:

//importing model
const toDoModel = require("../models/ToDoModel");

//creating controller function
const fetchAllToDosController = async (req, res) => {
  try {
     const { email} = req.params;
     console.log(email)
    const toDos = await toDoModel.find({ toDoEmail: {email:email} });
    res.status(200).json({
      success: true,
      message: "updated successfully",
      toDos,
    });
  } catch (err) {
    res.status(401).json({
      success: false,
      message: "Failed to fetch todo's",
      error: err.message,
    });
    console.log(err.message);
  }
};
module.exports = fetchAllToDosController;

我的数据库:

服务器对 Postman 的响应:

我的控制台日志:

我已经尝试console.log电子邮件,以检查它是否从url参数获取电子邮件,它成功地控制台记录它。我不明白为什么它给我空数组,而不是包含匹配的电子邮件的对象集合。

w1jd8yoj

w1jd8yoj1#

你的模型是一个对象,所以也可以用对象做过滤器。
它可以是:

const toDos = await toDoModel.find({ "toDoEmail.email" :email});

相关问题