简体   繁体   中英

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

So I'm playing with MongoDb database, I've used so far with Python but now I'm trying to conquer Node.js. I've connected to mongo database with mongoose. Configured following schema:

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);

I have filled database with some autamation procedure in python, and the problem I have is that somehow I got the two unwanted charaters \\n on beginning of my title string. I managed to find documents with Mongoose in Node, that has title item which are starting with \\n with:

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

I'm little bit newbie in javascript so I'm gonna ask a question which is the best way to replace the \\n with nothing (I suppose something like string.replace("\\n","") ) and update it back to my mongo database?

Suprisingly I think that I succeded with modification of my own code:

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

});

I have looped through the found documents and then saved new stuff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM