Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I get the id of each doc when saving an array of documents with mongoose?
    primarykey
    data
    text
    <p>I have two schemas that look like this: </p> <pre><code>var ToolBoxSchema = new Schema({ description: String, tools: [{type: ObjectId, ref: 'Tool'}] }); var Tool = new Schema({ name: String, model: String, }); </code></pre> <p>Let's say I have a new <code>ToolBox</code> that has a set of <code>Tools</code>. I have an array of <code>Tools</code> and would like to use the create method from mongoose to save these tools and then add a reference to the ToolBox.tools array for each tool. </p> <pre><code>var toolBoxModel = mongoose.model('ToolBox', ToolBoxSchema); var toolModel = mongoose.model('Tool', ToolSchema); var toolbox = new toolBoxModel(); var tool = new toolModel(); var toolsArray = getTools(); </code></pre> <p>Assume getTools() returns an array of tools with X number of elements. Ex: [{name: "screwdriver", model: "craftman 3000"}, {name: "drill", model: "black and decker"}]</p> <p>When I call the model's create method, how can I get a list of all of the documents that were saved?</p> <p>The example in the mongoose api docs shows each saved document being passed in as a parameter to the callback function, but if the number of elements in the array is different every time then I don't know how to get the id's of all the saved elements in the array. </p> <pre><code>var array = [{ type: 'jelly bean' }, { type: 'snickers' }]; Candy.create(array, function (err, jellybean, snickers) { if (err) // ... }); </code></pre> <p>Is there a way to get back an array of all the saved documents ...maybe something like this:</p> <pre><code>var toolsArray = [{name: "screwdriver", model: "craftman 3000"}, {name: "drill", model: "black and decker"}]; tool.create(toolsArray, function (err, arrayOfToolDocs) { if (err) { throw err; } for (var i = 0; i &lt; arrayOfToolDocs.length; i++) { toolbox.tools.push(arrayOfToolDocs[i].id); } toolbox.save(); }); </code></pre>
    singulars
    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.
    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