javascript - Node.js、mongoose 和 MongoDb - 替换多个文档中特定字符串中的字符

标签 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中的一些自动化程序填充了数据库,我遇到的问题是,不知何故,我在title字符串的开头得到了两个不需要的字符\n。我设法在 Node 中找到带有 Mongoose 的文档,该文档的标题项以 \n 开头,其中:

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

我是 javascript 的新手,所以我要问一个问题,将 \n 替换为空(我想类似于 string.replace("\n",""))并将其更新回我的 mongo 数据库的最佳方法是什么?

最佳答案

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

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!');
            }
        });
    }

});

我循环浏览了找到的文档,然后保存了新内容

关于javascript - Node.js、mongoose 和 MongoDb - 替换多个文档中特定字符串中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21786256/

相关文章:

javascript - multer npm : TypeError: Cannot read property 'path' of undefined

node.js - Id 没有从嵌套数组中删除

node.js - 使用 Mongoose 填充其他集合中的记录数

mongodb - 检查具有内部数组的文档数组的某些字段的重复项

javascript - 我的脚本需要刷新页面才能运行

javascript - 调整滚动条偏移量?

javascript - Backbonejs 集合获取错误检测 XHR 对象

javascript - 为什么我只得到一维数组?

c# - .NetStandard 2.0,MongoDB 驱动程序 : FileNotFoundException for MongoDB. Bson

javascript - 使用 django 提供 npm 包的最佳方式?