Jaguar Jaguar - 6 months ago 67
Javascript Question

How to add multiple ObjectIds using addToSet with Mongoose?

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);


Project.create({fileUrl: req.fileUrl}, (err, proj) => {
if (err) {
return res.status(400).send(err);
} else {
File.distinct('_id', {date: {"$lt": }}).exec((err, files) => {
if (err)
return (err)
var added = new File([files]) <-----THE PROBLEM
return res.status(200).send('OK');

//Usually I would do something like this if I were adding one subdocument to an array:

var foo = new File(file)


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);, saved){
      if (err)
        throw (err)

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.