【发布时间】:2022-09-25 18:01:54
【问题描述】:
我正在尝试使用节点和 mongoDB 保存我从网站中删除的数据,但我无法将其保存在数据库中。我能够将数据保存在数组(bdata)中并获取数据以显示在我的本地主机中,但不能保存到它。
非常感谢任何帮助。 先感谢您!
const axios = require(\'axios\');
const cheerio = require(\'cheerio\');
const express = require(\'express\');
const port = 4000;
const app = express();
const bodyParser = require(\'body-parser\');
const mongoose = require(\"mongoose\");
const Phones = require(\'./models/phones\');
mongoose.Promise = global.Promise;
mongoose.connect(\"mongodb://0.0.0.0:27017/testDatabase\");
app.set(\'view engine\', \'ejs\');
app.use(express.json())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.urlencoded({ extended: false }));
const url = \'https://scrapewebsite.com\';
const bdata = [];
async function scrapeSite(url) {
try {
const response = await axios.get(url);
const $ = cheerio.load(response.data);
const phones = $(\'.product-card\');
// loop through products
phones.each((i, phone) => {
if ($(phone).find(\"ins span.woocommerce-Price-amount.amount\")) {
price = $(phone).find(\"ins span.woocommerce-Price-amount.amount\").text();
} else if ($(phone).find(\".price.font-bold.text-lg.md:text-xl.text-black\")) {
price = $(phone).find(\".price.font-bold.text-lg.md:text-xl.text-black\").text();
}
article_name = $(phone).find(\".woocommerce-loop-product__title\").text();
link = $(phone).find(\"a\").attr(\"href\");
bdata.push({ \"article\": article_name, \"link\": link, \"price\": price });
});
//console.log(bdata);
return;
// iterate through all pages
const hasNext = $(\".next\").text();
if (hasNext.length > 0) {
next_page = $(\".next\").attr(\'href\');
scrapeSite(next_page);
}
console.log(next_page);
} catch (error) {
console.error(error);
}
}
scrapeSite(url);
app.get(\'/\', (req, res) => {
res.render(\'index\', { bdata: bdata });
});
app.listen(port, () => console.log(\'Example app listening on port \' + port));
还有我的架构
const mongoose = require(\'mongoose\');
const Schema = mongoose.Schema;
const PhonesSchema = new Schema({
article: String,
link: String,
price: String
});
module.exports = mongoose.model(\'Phones\', PhonesSchema);
-
中间的
return使后面的内容无法访问(从const hasNext开始......) -
我不认为将某些东西分配给
price会做任何事情。不是猫鼬专家,但如果它创建了一个将执行写入的实体,那么phone.price =可能是更新实体并写回数据库的预期方式。否则,我在这里看不到任何可能修改您的数据库的代码。我认为通常您还需要在某处拨打model.save(phone)电话。同样,我在您的代码中没有看到任何这些。 -
正如您所提到的,我设法使用 .save() 方法保存了数据。谢谢!
标签: javascript node.js mongodb express