所以我正在使用 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/