-1

I'm trying to update an existing document by increment a counter and pushing an object to an array.

Here's the schema for 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's 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

3 Answers 3

2

Answering my own question

I was able to solve the problem by changing:

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

Into this:

User.findById(req.user._id, function (err, user) { [...] });
Sign up to request clarification or add additional context in comments.

Comments

2

I think, if you would like to use findOne you need follow syntax:

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

2 Comments

This is the correct response. Currently there's a bug in the latest release (marked as fixed though) where they don't properly handle passing null for the fields property
You can pass an empty object, or modify line 175 of collection.js to add the check
0

Not sure about findById() vs. findOne(), but I've had problems with Mongoose objects returning Object.keys called on non-object while saving or updating with mal-formed data or data corresponding to an older schema. While initializing the document, Mongoose was expecting a subdocument of some kind, but the data in the database didn't match that.

For me it usually happens when I change schemas from a simple object (String, Number, etc.) to a more complex subdocument of some kind. The schema types are mixed up and the object won't load, not even to fix the problem. I had to go into my database using the native driver, search for mal-formed documents using the $type operator, and update them individually.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.