Mongoose insertMany - 缺少 createdAt

3

我正在使用mongoose开发我的Node微服务应用。

我有一个包含'createdAt'字段的模型,该字段是自动生成的:

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);

我尝试将一大批文档插入其中,就像这样:

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

由于某些原因,如果我插入单个文档,则会按预期创建'createdAt'。但是如果我使用insertMany函数,则不起作用,也不会创建'createdAt'(或created_at)。

这是正常的吗?
这是mongoose中的错误吗?

2个回答

1
您在这里没有使用mongoose schema。您正在使用默认的节点驱动程序,通过使用[schema] .collection.[method]。参考this,您可以直接使用RecordModel.insertMany,这样应该会添加时间戳。

好的了解。在这种情况下,正确的语法是什么? - Or Assayag
2
就像我之前所说的那样,不要使用 RecordModel.collection.insertMany,而是尝试使用 RecordModel.insertMany - Jonathan Nielsen
这个有用吗?我遇到了类似的问题,只不过我正在使用Notification.insertMany,其中Notification是上面导出的模型架构。对于我的情况,updatedAt被填充了,但是createdAt时间戳没有被填充。现在,我通过简单地手动将createdAt: new Date()添加到我在insertMany中使用的每个文档中来解决了这个问题。 - SKeney
@SKeney 请开一个新的问题,将你的代码复制粘贴进去并把链接发给我,我会看一下的 :) - Jonathan Nielsen
@JonathanNielsen https://stackoverflow.com/questions/72003775/model-insertmany-does-not-create-createdat-or-updatedat-timestamps . 这是一个链接。抱歉这么晚才回复,我忘了它了。到目前为止,我一直通过createdAt: Date.now()来解决它,但我很想弄清楚如何通过模式定义中的timestamps选项自动管理它。 - SKeney

0

不妨试试使用create而不是insertMany?

create触发中间件save(),支持时间戳。

Reference: Model.create

很遗憾,我现在无法尝试这个,上面只是基于Mongoose文档的描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接