簡體   English   中英

Node.js,mongoose和MongoDb-在多個文檔中替換某些字符串中的字符

[英]Node.js, mongoose and MongoDb - Replace character in certain string in multiple documents

因此,我正在玩MongoDb數據庫,到目前為止我已經在Python中使用過,但是現在我正在嘗試征服Node.js。 我已經用貓鼬連接到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中找到了貓鼬的文檔,該文檔的標題項以\\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!');
            }
        });
    }

});

我瀏覽了找到的文檔,然后保存了新內容

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM