Node.js,mongoose和MongoDb - 替换多个文档中某些字符串中的字符

时间:2014-02-14 17:55:14

标签: javascript node.js mongodb

所以我正在使用MongoDb数据库,到目前为止我已经使用过Python,但现在我正在尝试征服Node.js.我用mongoose连接到mongo数据库。配置以下架构:

var recipeSchema = new Schema({
    title: String,
    img: String,
    category: String,
    cook_time: String,
    method: String,
    person_count: String,
    short_desc:String,
    ingredients: [
        {
            amount: String,
            ingredient: String
        }
    ],
    recipe: String,
    advice: String

});
var Recipe = mongoose.model('Recipe', recipeSchema);

我已经在python中填充了一些自动化程序数据库,我遇到的问题是我在\n字符串的开头有两个不需要的字符title。我设法在Node中找到Mongoose的文档,其标题项以\n开头,其中包含:

Recipe.find({ title: /\n/ }, 'title', function (err, document) {
    if (err) return handleError(err);
    console.log(document)
})

我在javascript中有点新手所以我会问一个问题,这是用\n替换string.replace("\n","")的最好方法(我想像{{1}}之类的东西)并将其更新回来我的mongo数据库?

1 个答案:

答案 0 :(得分:0)

令人惊讶的是,我认为我成功修改了自己的代码:

Recipe.find({ title: /\n/ }, 'title', function (err, document) {

    for (i = 0, max = document.length; i < max; i++) {
        console.log(document[i]);
        var newTitle = document[i].title.replace(/\n/,"");
        document[i].title = newTitle;
        document[i].save(function (err) {
            if(err) {
                console.error('ERROR!');
            }
        });
    }

});

我已查找已找到的文件然后保存了新内容