mongodb 无法在insert上使用mongoose、nodejs创建时间序列集合

z18hc3ub  于 2023-06-29  发布在  Go
关注(0)|答案(1)|浏览(111)

我正在使用mongoose创建一个模式。我想将数据插入时间序列集合。我想同时插入和创建集合。所以我创建了我的mongoose schema,看起来像这样:

const mongoose = require('mongoose')
const Schema = mongoose.Schema;

const pmSchema = new Schema({
    aqius: Number,
    conc: Number
})
const MeasurementSchema = new Schema({
    ts: Date,
    pm1: Number,
    pr: Number,
    hm: Number,
    tp: Number,
    pm25: pmSchema,
    pm10: pmSchema,
});

const DailySchema = new Schema({
    time: Date,
    daily: [{
        type: MeasurementSchema,
    }],
    name: String,
}, {
    timeseries: {
        timeField: 'time',
    }
});

module.exports = mongoose.model('DailyMeasurement', DailySchema, 'daily-collection-ts')

然后我在一个cron作业中使用这个模式,它只是一个单独的js文件,它获取数据并将其保存在mongoDB中。cron作业看起来像这样:

const {MongoClient} = require("mongodb");
require('dotenv').config();
const DailyMeasurementModel = require('../app/Models/AQDataDaily');
const tokens = [
    process.env.aaaaa,
    process.env.ssssss,
    process.env.dddddd,
]
const urls = tokens.map(token => process.env.COMMON_DEVICE_URL + token)
const data_files = [
    '../test-data-json/asdasdasdasd.json',
    '../test-data-json/aaaa.json',
    '../test-data-json/sssss.json',
]
const getData = async () => {
    try {
        let data = []
        for (let i = 0; i < data_files.length; i++) {
            //FETCH DATA FROM JSON FILES FOR TESTING
            const response = require(data_files[i]);
            data.push(response)
            await saveData(data[i]);
          
        }
    } catch (error) {
        console.log('Error at getData: ', error);
    }
}

async function saveData(data) {
    const client = new MongoClient(process.env.MONGO_COMPASS_URI, {useUnifiedTopology: true});
    try {
        await client.connect();
        const db = client.db("iq-air-database");
        const coll = db.collection("daily-collection-ts");
        const timestamp = new Date().getTime();
        const newDailyMeasurement = new DailyMeasurementModel({
            time: timestamp,
            daily: data.historical.daily,
            name: data.name
        })

        try {
            // Save newDayMeasurement instance to database
            const result = await coll.insertOne(newDailyMeasurement)
            console.log('Document saved:', result);
        } catch (err) {
            console.error('Error saving document:', err);
        }
    } catch (error) {
        console.log('Error at the start of saveData: ', error);
    } finally {
        await client.close();
    }
}

getData()

数据正确保存在mongoDB中,但集合是常规集合,而不是时间序列集合。我检查了我的mongo版本,它足够高。我还使用mongoDB compass shell手动创建了一个时间序列集合。预期的结果是数据保存在时间序列集合中,而不是像现在这样保存在常规集合中。

von4xj4u

von4xj4u1#

由@user200492973(How to create Time Series Collection with Mongoose)提供的链接确实提供了解决方案。然而,在我看来,有时会创建一个时间序列集合,而在其他时候则会创建一个常规集合。
我不知道为什么。

相关问题