Mongoose insertMany - Missing createdAt

Viewed 599

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?

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.

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

Related