Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to put embedded document from one document into another document using Mongoose?
    primarykey
    data
    text
    <p>What I'm trying to do should be straight forward but for some reason I'm having real difficulties figuring this out. I have the following Mongoose schemas (simplified).</p> <pre><code>var Status = new Schema({ name : { type: String, required: true }, description : { type: String } }); var Category = new Schema({ statuses : [Status], // contains a list of all available statuses // some other attributes }); var Book = new Schema({ statuses : [Status], // preferably this would not be an array but a single document, but Mongoose doesn't seem to support that // some other attributes }); </code></pre> <p>Now, I want to do the following:</p> <ol> <li>Retrieve the Category document</li> <li>Find a particular embedded Status document (based on request param)</li> <li>Assign that particular embedded Status document to a particular Book document. I want to replace the existing Book status as at any given time there should only be one status set for a book.</li> </ol> <p>Here is what I'm currently doing:</p> <pre><code>mongoose.model('Category').findOne({_id: id}, function(err, category){ if(err) next(err); var status = category.statuses.id(statusId); // statusId available via closure book.statuses[0] = status; // book available via closure; trying to replace the existing status here. book.save(function(err){ if(err) next(err); next(); }); }); </code></pre> <p>The above seems to run fine and I don't get any errors. However, the new status is not saved to the document. Next time I output the updated Book document, it will still have the old status. I debugged this and the find() methods as well as setting the status seems to be fine. </p> <p>The only thing I can think of right now is that somehow the status value I'm assigning is not in the right format to be saved with Mongoose. Although, I would expect some kind of error message then. </p> <p>Or maybe there is a better way to do all of this anyway?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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