【问题标题】:Unable to use Model.findbyId in mongoose无法在猫鼬中使用 Model.findbyId
【发布时间】:2021-03-07 19:59:53
【问题描述】:

我将 MongoDB 与 nodejs、expressjs、ejs 和护照一起使用。我已设置 MVC 并正在从视图发送动态 URL。

这是我的 MongoDB 架构:

const companySchema = new mongoose.Schema({
    country: {
        type: String,
    },
    username: {
        type: String,
        unique: true,
    },
    password: {
        type: String,
    },
    vaccine: {
        name: String,
        price: Number,
    }
}, {
    timestamps: true
});

从视图中,我发送了一个格式为 /vaccine/{vaccine.name} 的 URL,其中vaccine.name 是架构中的数据。在服务器端,我正在对 URL 进行切片以获取确切的疫苗名称。这是我获取用户的查询:

const Company = require("../models/company");

module.exports.transaction_req = function (req, res) {
    if (req.isAuthenticated()) {
        const req_url = req.url.slice(1);
        // console.log(req_url);
        Company.findOne({vaccine.name: req_url}, function(err, user){
        return res.render('transaction');
        })

    }
    return res.redirect('/login');
};

它给出了这个错误,说我不能使用'。'在查询中:

Company.findOne({vaccine.name: req_url}, function(err, user){
                                ^
SyntaxError: Unexpected token '.'

使用给定的vaccine.name 获取用户的替代方法是什么?

【问题讨论】:

    标签: node.js mongodb express mongoose model-view-controller


    【解决方案1】:

    您不能在查询中使用属性访问器,请将您的 vaccine.name 括在引号中,如 'vaccine.name'

    【讨论】:

    • 是的,我刚刚发现了那个错误。但我现在面临一个新的问题。如何在不出现此错误的情况下呈现我的交易页面? Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    • @KrushnalPatel 您在查询调用中使用回调,这是一个异步操作。我建议您将处理程序重写为异步函数,并将查询重写为使用承诺(删除回调,并在查询对象上添加 .exec() 调用)。您也可以只放置 else 子句并用它包裹return res.redirect('/login');。发生此错误是因为您的代码已使用 return res.redirect('/login') 发送响应。
    猜你喜欢
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    • 2017-12-11
    • 2017-03-02
    • 1970-01-01
    • 2020-05-30
    • 2021-09-25
    相关资源
    最近更新 更多