I have two schemas that look like this:
var ToolBoxSchema = new Schema({
description: String,
tools: [{type: ObjectId, ref: 'Tool'}]
});
var Tool = new Schema({
name: String,
model: String,
});
Let's say I have a new ToolBox that has a set of Tools. I have an array of Tools 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.
var toolBoxModel = mongoose.model('ToolBox', ToolBoxSchema);
var toolModel = mongoose.model('Tool', ToolSchema);
var toolbox = new toolBoxModel();
var tool = new toolModel();
var toolsArray = getTools();
Assume getTools() returns an array of tools with X number of elements. Ex: [{name: "screwdriver", model: "craftman 3000"}, {name: "drill", model: "black and decker"}]
When I call the model's create method, how can I get a list of all of the documents that were saved?
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.
var array = [{ type: 'jelly bean' }, { type: 'snickers' }];
Candy.create(array, function (err, jellybean, snickers) {
if (err) // ...
});
Is there a way to get back an array of all the saved documents ...maybe something like this:
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 < arrayOfToolDocs.length; i++) {
toolbox.tools.push(arrayOfToolDocs[i].id);
}
toolbox.save();
});
You can get arguments passed into any function by using the arguments object. For example:
function argNum(){
console.log(arguments.length);
}
argNum('test',1,23,43); // Logs 4