简体   繁体   中英

How do I make sure that this variable gets defined?

I have this variable Blog which is a mongoose model. It gets defined here:

db.once("open", function(){
    var userSchema = new mongoose.Schema({
        username: String, 
        password: String
    });
    var blogSchema = new mongoose.Schema({
        title: String,
        content: String,
        userId: String
    });
    User = mongoose.model("User", userSchema); 
    Blog = mongoose.model("Blog", blogSchema);
});

I want to use app.get to generate a url that looks like /post/blogpost_id/edit so I tried to do this:

Blog.find(function (err, posts){
    app.get("/post/" + posts._id + "/edit/", checkAuth, function(req, res){
        res.render("edit.html", {
        pageTitle: "Edit",
        pages: {
            "Log Out": "/logout"
        },
        posts: posts
        });
    });
});

As you can imagine, that doesn't work. How can I fix this?

The reason is that Blog gets defined in an asynchronous callback, so your code gets further executed while node is waiting for the database to be opened and therefore will not be defined yet.

Also the defining of your route is extremely inefficient. You should define a route with a parameter : /post/:postID/edit and inside the callback check whether the post with the given ID exists. It will look like this afterwards (note that I don't know mongoose and wrote this after a quick check of the manual):

app.get("/post/:postID/edit/", checkAuth, function (req, res) {
    Blog.find({ _id: req.params.postID }, function (err, posts) {
        if (posts.length == 0) res.send(404, 'Not found');
        else // yadayada
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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