Ondrej Tokar
Ondrej Tokar

Reputation: 5070

Getting Object.keys called on non-object when creating mongoose schema

I've done some research and tried few things, like dropping the collection etc. Nothing has helped.

Code:

MongoClient.saveData = function(schemaDefinition, data, collectionName){
    console.log("Schema definition: "+schemaDefinition+" collection name: "+collectionName);
    var RecordSchema = new mongoose.Schema(schemaDefinition);//{ Email: String, FirstName: String});//({any: Schema.Types.Mixed });
    console.log("Schema created.");
    var RecordModel = mongoose.model(collectionName, RecordSchema);
    console.log("Model created. Inserting in batches.")
    RecordModel.insertMany(data)
    .then(function(mongooseDocuments) {
         console.log("Insertion was successful.");
    })
    .catch(function(err) {
        console.log("Error while inserting to DB.")
    });

The error:

/home/ubuntu/ds_queuesystem/node_modules/mongoose/lib/schema.js:381
  var keys = Object.keys(obj);
                    ^
TypeError: Object.keys called on non-object
    at Function.keys (native)
    at Schema.add (/home/ubuntu/ds_queuesystem/node_modules/mongoose/lib/schema.js:381:21)
    at new Schema (/home/ubuntu/ds_queuesystem/node_modules/mongoose/lib/schema.js:98:10)
    at Function.MongoClient.saveData (/home/ubuntu/ds_queuesystem/MongoClient.js:34:21)
    at /home/ubuntu/ds_queuesystem/DS_QueueSystem.js:84:18
    at nextTask (/home/ubuntu/ds_queuesystem/node_modules/async/dist/async.js:6627:18)
    at /home/ubuntu/ds_queuesystem/node_modules/async/dist/async.js:6621:17
    at /home/ubuntu/ds_queuesystem/node_modules/async/dist/async.js:339:31
    at /home/ubuntu/ds_queuesystem/node_modules/async/dist/async.js:840:20
    at /home/ubuntu/ds_queuesystem/DS_QueueSystem.js:143:3
    at null.<anonymous> (/home/ubuntu/ds_queuesystem/node_modules/csv-parse/lib/index.js:71:16)
    at EventEmitter.emit (events.js:117:20)
    at _stream_readable.js:920:16
    at process._tickCallback (node.js:415:13)

Schema definition:

var schemaDefinition = "{SCHID: String, Priority: Number, Status: String, Json: Schema.Types.Mixed})";

Upvotes: 0

Views: 392

Answers (1)

Dario
Dario

Reputation: 4035

schemaDefinition should be an Object, not a literal.

Try with:

var schemaDefinition = {
  SCHID: String,
  Priority: Number,
  Status: String,
  Json: Schema.Types.Mixed
};

Documentation: http://mongoosejs.com/docs/guide.html

Upvotes: 1

Related Questions