I am trying to use mongoose addToSet to add multiple ObjectIds to a sub-doc array. I've used a similar method for adding a single subdocument, but I'm trying to figure out how to add multiple subdocuments.
Project Model
import mongoose from 'mongoose';
var Schema = mongoose.Schema;
const ProjectSchema = new Schema({
title: {
type: String
},
files: [{
type: Schema.ObjectId,
ref: 'File'
}]
});
export default mongoose.model('Project', ProjectSchema);
File Model
import mongoose from 'mongoose';
var Schema = mongoose.Schema;
const FileSchema = new Schema({
fileUrl: {
type: String
},
date: {
type: Date
}
});
export default mongoose.model('File', FileSchema);
Controller
Project.create({fileUrl: req.fileUrl}, (err, proj) => {
if (err) {
console.log(err);
return res.status(400).send(err);
} else {
File.distinct('_id', {date: {"$lt": req.date }}).exec((err, files) => {
if (err)
return (err)
var added = new File([files]) <-----THE PROBLEM
proj.files.addToSet(added)
proj.save()
return res.status(200).send('OK');
})
}
});
//Usually I would do something like this if I were adding one subdocument to an array: (example)
var foo = new File(file)
proj.files.addToSet(foo)
proj.save()
You are very close! When you're passing the added variable, you are not sending the list of values through. You are basically sending a single object of arrays.
If you'd like to perform the addToSet function, try doing a simple iteration:
files.forEach(function(f) {
var added = new File(f)
proj.files.addToSet(added);
proj.save(function(err, saved){
if (err)
throw (err)
return;
})
});
You can find more examples of javascript iterators here:For-each over an array in JavaScript? There is an amazing and comprehensive list of options for you.