【问题标题】:sending data from Javascript to save in mongoDB through nodejs通过nodejs从Javascript发送数据以保存在mongoDB中
【发布时间】:2013-11-16 08:11:58
【问题描述】:

我正在尝试通过 node.js 服务器解析来自 javascript(博客文章头部和正文)的对象并将其保存在 mongoDB 中。

这是解析代码:

function saveState( event ) {

    var url = '';
    var postTitle = headerField.innerHTML;
    var article = contentField.innerHTML;
    var post = {
                    title: postTitle,
                    article: article
                };

    var postID = document.querySelector('.save').getAttribute('id');
    if(postID != "new"){
        url += "?id=" + postID
    }

    var request = new XMLHttpRequest();

    request.open("POST", "draft" + url, true);
    request.setRequestHeader("Content-Type", "application/json");
    request.send(post);
}

这被发送到这个节点服务器处理程序:

app.post('/draft', routes.saveDraft);

exports.saveDraft = function(req, res){
var id = url.parse(req.url, true).query.id;
var post = db.getPostByID(id);

if(id){
  console.log('post id' + id);
  db.savePost(id, req.body.head, req.body.article);
}
else{
  db.newPost(req.body.head, req.body.article);
}

res.render('editDraft.hbs', post); //send the selected post
}; 

然后,发送到以下 DB 函数之一:

exports.newPost = function (postTitle, article) {
new postCatalog({title:postTitle, 
                _id:1, 
                author:'temp', 
                AuthorID:2, 
                date:'2/3/12', 
                inShort:article.substring(0,100), 
                content:article ,
                published:false
            }).save(function (err, login) {
    if (err) {
        return console.log('error');
    }
    else {
        console.log('Article saved');
    }
});
}

exports.savePost = function (id, postTitle, article) {
postCatalog.find({_id: id}).save(function (err, login) {
    if (err) {
        return console.log('error');
    }
    else {
        console.log('Draft saved');
    }
});
}

现在,我只是无法让它工作.. 我是 node 新手,我真的可以使用你的帮助!

谢谢

编辑: 发送到 DB 保存函数的参数未正确写入。 但我仍然被困在同一个地方,数据正在发送但未正确保存。我认为我的 getPostByID 函数有问题,但我无法弄清楚:

exports.getPostByID =function (id) {
var post = postCatalog.find({_id: id}, function(err, post){
    if(err) {
        return handleError(err);
    }
    else{
        if(post > 0){
            post = post[0];
        }
        return post;
    }   
});
return post;
}

我正在使用 express(包括 bodyparser)和猫鼬。视图引擎是 hbs。

再次感谢。

【问题讨论】:

  • 你完全误解了 Node.js 的异步编程风格。请阅读一些教程并使用工作示例执行非常小的步骤。您的代码是同步样式,不起作用。
  • 感谢您的回复,但我相信即使程序是同步的,这也应该有效。
  • find 会返回一个游标,但不会返回实际结果。正如@hgoebl 所说,您不是在进行异步编程。 find 立即返回。

标签: node.js mongodb parsing


【解决方案1】:

您必须以异步方式编写它,例如您的 getPostByID:

exports.getPostByID = function (id, callback) {

    postCatalog.find({_id: id}, function(err, post) {
        if (err) {
            callback(err);
        }
        else if (post && post.length > 0) {
            callback(null, post[0]);
        }
        else {
            callback(null, null); // no record found
        }
    });

};   

这适用于您的整个代码。这是完全不同的,你尝试它的方式在 Node.js 下永远不会工作。

顺便说一句,有一个 mongo-driver 方法 findOne 更适合这种特殊情况,但我不想过多地更改您的代码。

【讨论】:

  • 感谢大家的cmets,击中书籍! (字面意思...)
  • 不客气!我们都必须绞尽脑汁才能对 Node.js 的方式感到温暖;-) 如果您将答案标记为正确和/或有帮助,那就太好了。
猜你喜欢
  • 2018-06-25
  • 1970-01-01
  • 1970-01-01
  • 2016-02-26
  • 2019-11-05
  • 1970-01-01
  • 1970-01-01
  • 2017-08-23
  • 1970-01-01
相关资源
最近更新 更多