【问题标题】:Using a value of an document as _id when importing this document to MongoDB using NodeJS使用 NodeJS 将此文档导入 MongoDB 时使用文档的值作为 _id
【发布时间】:2015-11-24 18:22:08
【问题描述】:

我正在尝试将一个对象导入 Mongo。但是当我尝试将 Object 的值用作 _id 时,它会失败。错误,即:“[CastError: Cast to ObjectID failed for value "11563195" at path "_id"]" 和后来的 "[Error: document must have an _id before Saving]"

我做错了什么?

// Read and import the CSV file.
    csv.fromPath(filePath, {
        objectMode: true,
        headers: keys
    })
    .on('data', function (data) {

        setTimeout(function(){

            var Obj = new models[fileName](data);
            Obj._id = Obj.SOME_ID;

            Obj.save(function (err, importedObj) {

                if (err) {

                    console.log(err);

                } else {

                    console.log('Import: OK');

                }
            });

        }, 500);
    })

这是使用的架构:

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

    var SomeSchema = new Schema(
        {
            SOME_ID: String,
            FIELD01: String,
            FIELD02: String,
            FIELD03: String,
            FIELD04: String,
            FIELD05: String,
            FIELD06: String,
            FIELD07: String,
            FIELD08: String,
            FIELD09: String,
            FIELD10: String,
            FIELD11: String,
            FIELD12: String,
            FIELD13: String
        },
        {
            collection: 'SomeCollection'
        });

module.exports = mongoose.model('SomeCollection', SomeSchema);

非常感谢您的时间和帮助。

【问题讨论】:

  • "11563195" 不是 ObjectID 的有效值
  • Obj 的架构是什么?您要在此处保存的数据是什么?
  • @SergioTulentsev 这是我创建的用于从 CSV 导入数据的模式,所有字符串。我需要使用一个字符串,即“11563195”作为_id。不可能吗?
  • 应该是可以的。一定是你做错了什么。
  • 需要查看您的猫鼬模式。

标签: node.js mongodb mongoose


【解决方案1】:

默认情况下,mongoose 会验证 _id 字段是否为 MongoId。如果您想在 _id 字段中存储 MongoId 以外的内容,则需要为 _id 字段指定不同的类型。

var SomeSchema = new Schema({
    _id: { type: String, required: true }
}

【讨论】:

  • 这正是我想要的!谢谢。
猜你喜欢
  • 2015-11-08
  • 2017-02-25
  • 1970-01-01
  • 1970-01-01
  • 2020-09-18
  • 2021-10-29
  • 2021-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多