TypeError: Object.keys, thrown when there is no object when updating a document

I am trying to update an existing document by increasing the counter and pushing an object to an array.

Here is the diagram for the user:

var UserSchema = new Schema({ [...] posts: { totalWords: { type: Number, min: 0, default: 0 }, _entries: [ { words: { type: Number, min: 0 }, body: { type: String }, date: Date } ] }, }); 

And here is the update code:

 var newPost = { words: req.body.words, body: req.body.entry, date: new Date() }; User.findOne(req.user._id, function (err, user) { var previous = user.posts.totalWords; user.posts.totalWords = previous + newPost.words; user.posts._entries.push(newPost); user.save(function (err) { if (err) return res.send(400, err); return res.json(newPost); }); }); 

I get the following error:

 [TypeError: Object.keys called on non-object] 

Any ideas on how to solve this?

0
source share
3 answers

Answering my question

I managed to solve the problem by changing:

 User.findOne(req.user._id, function (err, user) { [...] }); 

In it:

 User.findById(req.user._id, function (err, user) { [...] }); 
+2
source

I think if you want to use findOne, you need to follow the syntax:

User.findOne ({'_ id': req.user._id}, {}, function (err, user) {...});

+2
source

Not sure about findById() vs. findOne() , but I had problems with Mongoose objects returning Object.keys called on non-object when saving or updating with malformed data or data that matches the old schema. During initialization of the document, Mongoose was expecting some kind of subdocument, but the data in the database did not match this.

For me, this usually happens when I change the scheme from a simple object ( String , Number , etc.) to a more complex incomplete document. The types of circuits are mixed, and the object does not load, not even to fix the problem. I had to go into my database using my own driver , look for documents with incorrect design using the $type operator, and update them individually.

0
source

Source: https://habr.com/ru/post/1201270/


All Articles