简体   繁体   English

Mongoose 无法将“”的属性设置为未定义,每当我尝试创建新条目时。即使模式被声明为正确

[英]Mongoose cannot set property of “ ” to undefined,Whenever i try to create a new entry.Eventhough the schema is declared right

im building a support portal webiste.Where i have to record which user is raising the ticket.我正在建立一个支持门户网站。我必须在哪里记录哪个用户正在提高票证。 Im using passport so i can get the username and _id through req.user.Im using express and MongoDB Atlas as my database.I have saved my database schemas on a seaparate folder called models.我使用护照,所以我可以通过 req.user 获取用户名和 _id。我使用expressMongoDB Atlas作为我的数据库。我已将我的数据库模式保存在名为模型的单独文件夹中。 Here is the schema file:这是架构文件:

   const mongoose=require("mongoose");

const supportSchema=new mongoose.Schema({
    type:String,
    comment:String,
    date:String,
    status:String,
    author:{
        id:{
            type:mongoose.Schema.Types.ObjectId,
            ref:"User"
        },
        username:String
    }
})

module.exports=mongoose.model("Support",supportSchema);

and here is the express side of things:这是事情的明确方面:

    //posting support to admin
app.post("/admin/support",isLoggedIn,function(req,res){
    const data={
        type:req.body.type,
        comment:req.body.comment,
        status:"Pending"
    }
    Support.create(data,function(err,newsupport){
        console.log(req.user);
        if(err){
            console.log(err);
        }else{
            //add username and id to ticket
             Support.author.id=req.user._id;
             Support.author.username=req.user.username;
            // save ticket
            Support.save();
            res.redirect("/home");
        }
    })
})

As we can see in the schema above, i have defined author and inside author i have defined id.Im running into a error whenever im trying to create a ticket.It tells me "Cannot set property 'id' of undefined".正如我们在上面的架构中看到的,我已经定义了作者和内部作者,我已经定义了 id。每当我尝试创建票证时,我都会遇到错误。它告诉我“无法设置未定义的属性 'id'”。 I even crosschecked by console logging req.user(which im able to access inside the route).我什至通过控制台日志记录 req.user 进行了交叉检查(我能够在路由内部访问)。

I have required the schema in app.js我需要 app.js 中的架构

const Support=require("./models/newsupport");

PS:name of the file is newsupport. PS:文件名是newsupport。 i have configured mongodb connection like so:我已经像这样配置了 mongodb 连接:

mongoose
.connect('mongodb+srv://saidarshan:R@mb02501@cluster0-wjhf4.mongodb.net/project?retryWrites=true&w=majority', {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
    useUnifiedTopology: true
})
.then(() => {
    console.log('Connected to DB');
})
.catch((err) => {
    console.log('ERROR', err.message);
});

Please help me out with this.Thank you请帮我解决这个问题。谢谢

I'm not seeing where there is a new variable for the Support constructor to live while you're working on it.在您处理Support构造函数时,我没有看到哪里有新变量可以存在。 Try something like let newTicket = Support.create(... and then set newTicket.author.id , etc.尝试类似let newTicket = Support.create(...然后设置newTicket.author.id等。

The Schema is declared right, but the you are trying to save author (subdocument) on the Schema itself, and not an actual document. Schema 被声明为正确,但您试图将作者(子文档)保存在 Schema 本身上,而不是实际文档。

    Support.author.id=req.user._id;
    Support.author.username=req.user.username;
    // save ticket
    Support.save();

You want to perform that save on the newly created document , and not the Schema.您希望在新创建的文档上执行该保存,而不是 Schema。 Like this:像这样:

app.post("/admin/support",isLoggedIn,function(req,res){
    const data={
        type:req.body.type,
        comment:req.body.comment,
        status:"Pending"
    }
    Support.create(data,function(err,newsupport){
        console.log(req.user);
        if(err){
            console.log(err);
        }else{
            //add username and id to ticket
             newsupport.author.id=req.user._id;
             newsupport.author.username=req.user.username;
            // save ticket
            newsupport.save();
            res.redirect("/home");
        }
    })
})

Of course, another options will be to combine all the objects (document and the subdocument) together and do it all in one save so you can save yourself from having two queries to perform one task.当然,另一种选择是将所有对象(文档和子文档)组合在一起并在一次保存中完成所有操作,这样您就可以避免使用两个查询来执行一项任务。

const data={
        type:req.body.type,
        comment:req.body.comment,
        status:"Pending",
        author: {
            id: req.user._id,
            username: req.user.username
        }
    }

And you can just pass it to the Support.create and never bother about calling save method again on the created document.您可以将其传递给Support.create ,而不必再为创建的文档调用save方法而烦恼。

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

相关问题 Mongoose 模式无法读取未定义的属性“密码” - Mongoose schema Cannot read property 'password' of undefined 每当我尝试访问 record.username 时,我都会收到“TypeError: Cannot read property 'username' of undefined” - I am getting "TypeError: Cannot read property 'username' of undefined" whenever I try to access record.username 无法设置未定义的属性“ new_form” - Cannot set property 'new_form' of undefined Express.js猫鼬:TypeError无法设置未定义的属性 - Express.js mongoose: TypeError Cannot set property of undefined 'TypeError:无法设置未定义的属性'create'? - 'TypeError: Cannot set property 'create' of undefined'? 无法在新Schema.extend中读取未定义的属性“ forEach” - Cannot read property 'forEach' of undefined at new Schema.extend 每当我尝试创建新的反应应用程序或尝试启动现有的反应应用程序时出现错误 - Getting error whenever I try to create new react app or try to start existing react app 为什么我得到,无法设置未定义的属性 - why i get, Cannot set property of undefined 无法读取未定义的属性“类型” —使用猫鼬Schema.Types.ObjectId - Cannot read property 'Types' of undefined — using mongoose Schema.Types.ObjectId 无法设置未定义的属性“” - Cannot set property " " of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM