[英]Check if document already exists and if yes then update, otherwise create new - Mongoose
[英]How to check from Mongoose timestamps if the document already exists?
我正在用node.js + puppeteer + mongoose構建一個Web爬蟲。 我從網頁上獲取數據,並且可以將其保存到數據庫中。 下一步是能夠檢查文檔是否已存在於數據庫中。 一直在尋找並嘗試許多方法而沒有成功。 這是我的代碼部分,它將數據保存到db:
try {
const newCar = new Car({
make: make,
model: model,
year: year,
km: km,
price: price
});
let saveCar = await newCar.save();
console.log(saveCar);
console.log('car saved!');
} catch (err) {
console.log('err' + err);
}
在我的模式中,我添加了時間戳選項:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const carSchema = new Schema({
make: {
type: String
},
model: {
type: String
},
year: {
type: String
},
km: {
type: String
},
price: String
}, {timestamps: true });
module.exports = mongoose.model('Car', carSchema);
因此,我希望有人可以以此將我推向正確的方向。 有沒有一種方法可以使用createdAt時間戳檢查數據庫中是否已存在文檔,並在抓取時跳過該文檔?
編輯。 我一直在嘗試使用該哈希解決此問題。 這是我的代碼:
const hash = md5(assetsUrl);
const existingCar = Car.find({
'hash': { $exists: true }
});
if (!existingCar) {
try {
const newCar = new Car({
make: make,
model: model,
year: year,
km: kmInt,
price: priceInt,
currency: currencyString,
carUrl: carUrl,
imageUrl: imageUrls,
hash: hash
});
let saveCar = await newCar.save();
console.log(saveCar);
console.log('car saved!');
} catch (err) {
console.log('err' + err);
}
} else {
console.log('car already in db');
}
這是行不通的,每次代碼都會落到else塊中。 我在這里想念什么?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.