繁体   English   中英

卡在 NodeJS mongoDB find() 查询上

[英]Stuck on NodeJS mongoDB find() Query

我无法编写正确的查询。 我正在尝试检查用户是否已存在于数据库中,它将在登录成功响应中做出响应。 此代码在工作 position 问题在于查询。 我希望有人会帮助

function login() {
    app.post("/login/", async(req, res) => {

        const query = new Model({
            email: req.body.email,
            password: req.body.password,
        });
        const cursor = Model.find(query);  // (*Here's the problem*)
        console.log(cursor);
 if (query === cursor) {**strong text**
            console.log(query);
            res.send("login successfully");
        } else {
            console.log(query);
            res.send("user does not exist ");
        }
    });
}

login();

// Model and Schema

const LoginSchema = new mongoose.Schema({
    email: { type: String, required: true },
    password: { type: String, required: true },
});
const Model = mongoose.model("login_details", LoginSchema);

// Registeration Phase
function registration() {
    app.post("/register/", async(req, res) => {
        const model = new Model({
            email: req.body.email,
            password: req.body.password,
        });
        const result = await model.save();
        console.log(result);
        res.send(model);
    });
}

// Headers

const express = require("express");
const app = express();
const mongoose = require("mongoose");
app.use(express.json());
app.use(express.urlencoded({ extend: true }));

//


您以错误的方式使用 Mongoose。 尝试这个。

const result = await Model.find({
        email: req.body.email,
        password: req.body.password,
    }); 

您的代码有问题

1-您不需要使用new Model({})来查询

2-您正在使用.find()返回一个数组,请改用findOne()

3-您正在尝试检查 mongoose model (带有_id )是否等于没有_id的查询,这将不起作用

4- 在 function 的末尾使用 return (不会影响这里的功能,但最好不要遇到错误,例如cannot set headers after they're sent

可能的解决方案

function login() {
  app.post("/login/", async (req, res) => {

    const cursor = await Model.findOne({
      email: req.body.email,
      password: req.body.password,
    });
    console.log(cursor);
    if (cursor) {
      console.log(cursor);
      return res.send("login successfully");
    } else {
      return res.send("user does not exist ");
    }
  });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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