Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy mongoose replaces subdocuments with "[object Object]"?
    text
    copied!<p>I'm encountering weird behavior with embedded docs and I don't know if I do something wrong or is it a bug.</p> <p>This is my model:</p> <pre><code>var mg = require('mongoose') , S = mg.Schema; var subject = new S({ name: String , properties: [{ name: String , value: String }] }); module.exports = mg.model('Subject',subject); </code></pre> <p>When I try to add a property, it somehow gets converted into <code>"[object Object]"</code>:</p> <pre><code> console.log(req.body); // --&gt; { name: 'height', value: 120 } console.log(typeof req.body); // --&gt; object ob.Subject.findByIdAndUpdate(req.params.id, {$push: {properties: req.body}}, function(err, doc) { if(err) throw err; res.send(doc); }); </code></pre> <p>The returned <code>doc</code> is:</p> <pre><code>{_id: '...', name: 'sss', properties:[ "[object Object]" ]} </code></pre> <p>I used mongo CLI to inspect the document in the database and put proper values in it. </p> <pre><code>//the document as seen in mongo CLI: { _id: '...', name: 'sss', properties: [ "[object Object]", {name: "aaa", value: "bar"} ] } </code></pre> <p>Then I tried this:</p> <pre><code>ob.Subject.findById(id, function(err, doc) { res.send(doc); } </code></pre> <p>And then the returned doc is:</p> <pre><code>{ _id: '...', name: 'sss', properties:[ "[object Object]", "[object Object]" ] } </code></pre> <p>I think that, what's happening is mongoose somehow converts the subdocument into this string. Moreover, I don't think that this is my, or <code>res.send()</code> fault because:</p> <ul> <li>I'm not using <code>toJson</code> or <code>toObject</code> explicitly, I don't handle JSON conversion at all</li> <li><code>res.send()</code> is not an issue because even if I <code>util.inspect</code> the value - it's the same</li> <li>invalid conversion seems to happen both at write and read via mongoose</li> </ul> <p>Have you ever encountered similar behavior? Is there a way around that?</p> <p>I just started with mongoose and don't have an idea how to fallback to mongodb native to update and fetch documents and check if this behavior persists (I doubt). </p> <p>Any helpful hints appreciated :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload