Nello schema utente sottostante c'è un campo foobar.events
, che sto provando a inserire nuovi hash (che vengono ricevuti da una richiesta POST API) a.Node e Mangusta - Errore durante il salvataggio: TypeError: Object.keys chiamato non-object
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
}]
}
});
E qui è la logica per quella rotta espresso:
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;
});
Il metodo find
viene eseguito con successo, ma il seguente errore viene generato quando si tenta di salvare nel database: Error on save: TypeError: Object.keys called on non-object
- qualche idea del perché questo errore viene generato?
This thread had a similar problem, ma la modifica di findOne
a findById
ha interrotto la query dell'utente.
Come nota a margine, questo è ciò che viene restituito nella req.body
dal API:
{ events:
[ { action: 'updation',
timestamp: 1408846680,
user_xid: 'aguxwNqb_Xg87buMyP6Wiw',
type: 'move',
event_xid: 'vhAkgg1XwQvLynAkkCc8Iw' } ],
notification_timestamp: 1408846680 }
Ed ecco ciò che è restituito dal metodo User.findOne
{ __v: 17,
_id: 53f7d23e432de20200970c10,
foobar:
{ id: 'aguxwNqb_Xg87buMyP6Wiw',
name: 'Test User',
token: 'W3AjaI7_iOWilcKRpmxenQWi',
events: [] }
}
In che modo 'findById' ha interrotto la query dell'utente? L'errore sembra che il valore della variabile 'utente' non abbia il tipo corretto. Che aspetto ha l'utente quando viene registrato? – wdberkeley
Il campo 'user_xid' si collega a un utente specifico, ecco perché viene utilizzato il metodo' findOne'. Ho aggiornato la domanda per includere il registro 'user' – Anconia
Potrebbe essere un problema con il tuo schema. La riga che dice 'type: {type: String}' dovrebbe probabilmente essere qualcosa come 'event_type: String'. Non sono sicuro che ciò abbia a che fare con il problema, mi sembra strano. – ctlacko