Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose insertMany - Missing createdAt

I'm using mongoose in my Node micro service application.

I have a model with 'createdAt' that created automatically:

const mongoose = require('mongoose');

const recordSchema = new mongoose.Schema({
    source: {
        type: String,
        required: true,
        trim: true,
        lowercase: true
    },
    coin: {
        type: String,
        required: true,
        trim: true,
        lowercase: true
    },
    rate: {
        type: Number,
        required: true
    },
    isError: {
        type: Boolean,
        required: true
    },
}, { timestamps: { createdAt: 'created_at' } });

module.exports = mongoose.model('Record', recordSchema);

And I try to insert a bulk of documents into it, like this:

// Save the fetched data into the database.
const saveCoinsData = (coinsData) => {
    RecordModel.collection.insertMany(coinsData, (err) => {
        if (err) { logger.error(err); }
    });
};

For some reason, if I insert a single document the 'createdAt' is created as expected. But if I use the insertMany function, it's not working and no 'createdAt' (or created_at) is created.

Is this normal?
Is this a bug in mongoose?

like image 300
Or Assayag Avatar asked Oct 23 '25 14:10

Or Assayag


2 Answers

You're not using mongoose schema here. You're using default node drivers by using [schema].collection.[method]. Referring to this you can just use RecordModel.insertMany instead, that should add the timestamps.

like image 150
Jonathan Nielsen Avatar answered Oct 26 '25 03:10

Jonathan Nielsen


Instead of insertMany, maybe try create?

create triggers middleware save() which supports timestamps.

Reference: Model.create

Unfortunately I cannot try this now, above is just based on Mongoose documentations

like image 44
hoistyler Avatar answered Oct 26 '25 03:10

hoistyler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!