Nodejs mongodb数据库插入异常

Nodejs mongodb数据库插入异常

错误如下,标签tags直接变成了post文章的内容,而tags的内容不见了,post变成null了,其中tags是一个数组。 { “_id” : ObjectId(“53828de1f6e4e37012b0114e”), “name” : “wangxu”, “time” : { “date” : ISODate(“2014-05-2 6T00:42:09.896Z”), “year” : 2014, “month” : “2014-5”, “day” : “2014-5-26”, “hour” : “2014-5-26-8”, “minut e” : “2014-5-26 8:42” }, “title” : “nodejs高级编程”, “tags” : “就是这样的优惠,你可以抗拒吗?”, “post” : null, “comments” : [ ] }

post.js模板存储部分如下:

function Post(name,title,tags,post){ this.name = name; this.title = title; this.tags = tags; this.post = post; } Post.prototype.save = function(callback){ var date = new Date(); //存储各种时间格式方便以后使用 var time = { date : date, year : date.getFullYear(), month : date.getFullYear()+’-’+(date.getMonth()+1), day : date.getFullYear()+’-’+(date.getMonth()+1)+’-’+date.getDate(), hour : date.getFullYear()+’-’+(date.getMonth()+1)+’-’+date.getDate()+’-’+date.getHours(), minute : date.getFullYear()+’-’+(date.getMonth()+1)+’-’+date.getDate()+’ ‘+date.getHours()+’:’+date.getMinutes() }; //要存入数据库的文档 var post = { name : this.name, time : time, title : this.title, tags : this.tags, post : this.post, comments : [] }; //打开数据库 mongodb.open(function(err,db){ if(err){ return callback(err); } //读取posts集合 db.collection(‘posts’,function(err,collection){ if(err){ mongodb.close(); return callback(err); } //将信息插入posts集合 collection.insert(post,{safe:true},function(err){ mongodb.close(); if(err){ return callback(err); } callback(null); }); }); }); };

post.ejs如下: <%include header.ejs%> <form method=“post”> <body> <label>标题</label><br/> <input type=“text” name=“title” id=“title”> <p> <label>标签(最多三个)</label><br/> <input type=“text” name=“tag1” /> <input type=“text” name=“tag2” /> <input type=“text” name=“tag3” /> <p> <label>内容</label><br/> <textArea type=“text” name=“post” id=“post” rows=“5” cols=“100”></textArea> <p> <button type=“submit”>发表</button> </body> </form> <%include footer.ejs%>

请各位给看看,不胜感激。谢谢。。。


4 回复

根据你的描述,问题似乎出在 post.ejs 模板中表单数据的处理上。从你提供的 post.js 中的数据结构来看,tags 应该是一个数组,而不是字符串。但在 post.ejs 中,标签被当作单独的文本输入字段来处理。

为了解决这个问题,你需要修改 post.ejs 文件中的表单,使其能够正确地收集多个标签并将其作为数组传递给服务器端。以下是修改后的 post.ejs 示例:

<%- include('header.ejs') %>

<form method="post">
    <body>
        <label>标题</label><br/>
        <input type="text" name="title" id="title"><br/>

        <label>标签(最多三个)</label><br/>
        <input type="text" name="tags[]" value=""><br/>
        <input type="text" name="tags[]" value=""><br/>
        <input type="text" name="tags[]" value=""><br/>

        <label>内容</label><br/>
        <textarea name="post" id="post" rows="5" cols="100"></textarea><br/>

        <button type="submit">发表</button>
    </body>
</form>

<%- include('footer.ejs') %>

在这个例子中,我们把标签的输入字段改为数组形式,即 name="tags[]"。这样,当表单提交时,浏览器会自动将这些输入字段作为一个数组传递给服务器。

接下来,你需要在 post.js 中正确处理这些数据。假设你在后端接收到了这些数据,可以这样处理:

app.post('/add-post', (req, res) => {
    const { name, title, tags, post } = req.body;

    // 确保 tags 是一个数组
    if (!Array.isArray(tags)) {
        tags = tags.split(',').map(tag => tag.trim());
    }

    const newPost = new Post(name, title, tags, post);

    newPost.save((err) => {
        if (err) {
            console.error(err);
            return res.status(500).send('保存失败');
        }
        res.redirect('/success'); // 假设有一个成功页面
    });
});

这段代码首先检查 tags 是否已经是数组,如果不是,则将其按逗号分隔成数组。然后创建一个新的 Post 实例,并调用其 save 方法来保存到数据库。

通过这种方式,你应该能解决标签丢失的问题。希望这对你有所帮助!


有人知道吗?请赐教,很捉急啊

终于解决了,实在太低级了。。。

根据你的描述,问题出在表单数据的处理上。你在 post.ejs 文件中定义了多个标签输入框(tag1, tag2, tag3),但是在 post.js 模板中,你只接收了一个 tags 字段,并且将其作为字符串处理。这导致所有标签都被合并成一个字符串,并覆盖了 post 字段。

以下是解决方案:

  1. 修改表单:将标签字段改为数组形式提交。
  2. 修改后端处理逻辑:正确地处理这些标签数组。

修改 post.ejs

将标签输入框改为数组形式:

<form method="post">
    <body>
        <label>标题</label><br/>
        <input type="text" name="title" id="title">
        <p>
        <label>标签(最多三个)</label><br/>
        <input type="text" name="tags[]" /> 
        <input type="text" name="tags[]" />
        <input type="text" name="tags[]" />
        <p>
        <label>内容</label><br/>
        <textarea type="text" name="post" id="post" rows="5" cols="100"></textarea>
        <p>
        <button type="submit">发表</button>
    </body>
</form>

修改 post.js

save 方法中正确处理标签数组:

function Post(name, title, tags, post) {
    this.name = name;
    this.title = title;
    this.tags = tags;
    this.post = post;
}

Post.prototype.save = function (callback) {
    var date = new Date();
    // 存储各种时间格式方便以后使用
    var time = {
        date: date,
        year: date.getFullYear(),
        month: date.getFullYear() + '-' + (date.getMonth() + 1),
        day: date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate(),
        hour: date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + '-' + date.getHours(),
        minute: date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes()
    };
    // 要存入数据库的文档
    var postDoc = {
        name: this.name,
        time: time,
        title: this.title,
        tags: this.tags,
        post: this.post,
        comments: []
    };

    // 打开数据库
    mongodb.open(function (err, db) {
        if (err) {
            return callback(err);
        }
        // 读取posts集合
        db.collection('posts', function (err, collection) {
            if (err) {
                mongodb.close();
                return callback(err);
            }
            // 将信息插入posts集合
            collection.insert(postDoc, { safe: true }, function (err) {
                mongodb.close();
                if (err) {
                    return callback(err);
                }
                callback(null);
            });
        });
    });
};

这样,标签将会以数组的形式被正确保存到 MongoDB 中。

回到顶部