Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node & Mongoose - Error on save: TypeError: Object.keys called on non-object

In the below user schema there is a foobar.events field, that I am trying to push new hashes (that are received from an API POST request) to.

var userSchema = mongoose.Schema({

    foobar: {
        id           : String,
        token        : String,
        email        : String,
        name         : String,
        events       : [{
            action          : String,
            timestamp       : Date,
            user_xid        : String,
            type            : {type: String},
            event_xid       : String    
        }]
    }

});

And here is the logic for that Express route:

app.post('/foobar/post', function(req, res) {
    var jb_user_xid  = req.body['events'][0]['user_xid'];
    var jb_timestamp = req.body['events'][0]['timestamp'];
    var jb_action    = req.body['events'][0]['action'];
    var jb_type      = req.body['events'][0]['type'];
    var jb_event_xid = req.body['events'][0]['event_xid'];

    User.findOne({'foobar.id':jb_user_xid}, function(err, user) {
        console.log(user);
        user.foobar.events.push({
            user_xid: jb_user_xid,
            timestamp: jb_timestamp,
            action: jb_action,
            type: jb_type,
            event_xid: jb_event_xid
        });
        user.save(function(err) {
            if (err){ 
                console.log("Error on save: " + err);
            }
            else {
                console.log("Save successful");
            }
        });
    });

    res.writeHead(200);
    res.end();
    return;
});

The find method is executed successfully, but the following error is thrown when trying to save to the database: Error on save: TypeError: Object.keys called on non-object - any idea why this error is being thrown?

This thread had a similar problem, but changing the findOne to findById broke my user query.

As a side note, this is what is returned in req.body from the API:

{  events:
    [ { action: 'updation',
        timestamp: 1408846680,
        user_xid: 'aguxwNqb_Xg87buMyP6Wiw',
        type: 'move',
        event_xid: 'vhAkgg1XwQvLynAkkCc8Iw' } ],
   notification_timestamp: 1408846680 }

And here is what's returned from the User.findOne method

{ __v: 17,
   _id: 53f7d23e432de20200970c10,
   foobar:
    { id: 'aguxwNqb_Xg87buMyP6Wiw',
      name: 'Test User',
      token: 'W3AjaI7_iOWilcKRpmxenQWi',
      events: [] }
}
like image 904
Anconia Avatar asked Aug 27 '14 19:08

Anconia


People also ask

What is node used for?

Node allows developers to write JavaScript code that runs directly in a computer process itself instead of in a browser. Node can, therefore, be used to write server-side applications with access to the operating system, file system, and everything else required to build fully-functional applications. Node.

What is this node?

A node is a point of intersection/connection within a data communication network. In an environment where all devices are accessible through the network, these devices are all considered nodes. The individual definition of each node depends on the type of network it refers to.

Why is it called node?

The official name is actually Node . Originally it was designed for use as a web application, but the author realized it could be used for more general purposes and renamed it to node.

What is an example node?

Examples of nodes include bridges, switches, hubs, and modems to other computers, printers, and servers. One of the most common forms of a node is a host computer; often referred to as an Internet node. 2. In graph theory, a node is a unit of data on a graph, connected to other nodes by edges.

What is NodeJS?

What is Node.js? 1 Node.js is an open source server environment 2 Node.js is free 3 Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.) 4 Node.js uses JavaScript on the server

What is the meaning of node?

Definition of node 1 a : a pathological swelling or enlargement (as of a rheumatic joint) b : a discrete mass of one kind of tissue enclosed in tissue of a different kind 2 : an entangling complication (as in a drama) : predicament

What is a node in cryptocurrency?

A node is a connected computer in a cryptocurrency network that can receive, send, and create information related to virtual coins. A server node runs back-end applications that access data on a shared network. Server nodes complement client nodes, which run front-end data-retrieving applications.

What is a node in a smart home network?

For example, within the physical network of a smart home domotics system, each home appliance capable of transmitting or receiving information over the network constitutes a node. However, a passive distribution point such as a patch panel would not be considered a node.


2 Answers

This error was actually due to old data within my Mongo database. The events field was full of extra strings. I deleted these and my original code began working successfully. No changes to the above code were necessary.

like image 109
Anconia Avatar answered Sep 28 '22 06:09

Anconia


I tried your code and it works perfectly.. for me.. try to check mongoose module version or something.if u have still problem please do it using update function rather than save..It would be more performance oriented.

this is the following i used

    var mongoose = require('mongoose');
    mongoose.connect('mongodb://localhost/test');
    var db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', function callback () {
      // yay!
    });
    var userSchema = mongoose.Schema({

        foobar: {
            id           : String,
            name         : String,
            events       : [{
                action          : String,
                timestamp       : Date,
                user_xid        : String,
                type            : {type: String},
                event_xid       : String    
            }]
        }

    });







    var User =  mongoose.model('user', userSchema);

    /*
    //used for saving.
    var person =  new User({  foobar:
        { id: 'aguxwNqb_Xg87buMyP6Wiw',
          name: 'Test User',
          token: 'W3AjaI7_iOWilcKRpmxenQWi',
          events: [] }
    });
    person.save(function(err,data){
    console.log(err);
    console.log(data);
    })

    */


    User.findOne({'foobar.id':'aguxwNqb_Xg87buMyP6Wiw'}, function(err, user) {
            console.log(user);
            user.foobar.events.push({ action: 'updation',
            timestamp : 1408846680,
            user_xid: 'aguxwNqb_Xg87buMyP6Wiw',
            type: 'move',
            event_xid: 'vhAkgg1XwQvLynAkkCc8Iw' });
            user.save(function(err) {
                if (err){ 
                    console.log("Error on save: " + err);
                }
                else {
                    console.log("Save successful");
                }
            });
        });
like image 20
vimalpt Avatar answered Sep 28 '22 06:09

vimalpt