Asaf Baibekov
Asaf Baibekov

Reputation: 375

Mongoose - push object id to array of ObjectIds

According to the schema below:

const mongoose = require('mongoose')

var schema = new mongoose.Schema({
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        unique: true,
        required: true
    },
    files: {
        type: [mongoose.Schema.Types.ObjectId],
        ref: 'File',
        required: true
    }
}, { timestamps: true })

module.exports = mongoose.model('Model', schema);

I created a file document and I'm trying to take its ID and push it to a files array. Here is what I've already tried (does not work):

Model.findOneAndUpdate(
    { user: user._id },
    { $push: { files: file._id  } },
    { upsert: true, new: true, runValidators: true }
)

I also checked that file._id is not null/undefined and there is an ObjectId there:

{
    "model": {
        "files": [],
        "_id": "5f90c117624d199c9c7984af",
        "user": "5f31d5fe37d233f359d82f5a",
        "__v": 0,
        "createdAt": "2020-10-21T23:15:35.025Z",
        "updatedAt": "2020-10-22T07:16:53.843Z"
    }
}

How can I insert the file's ID into the files array?

EDIT: I saw the DB after I ran this command and I saw that the ObjectId pushed the array but I cannot is it in the output.

How can I solve it?

Upvotes: 4

Views: 3493

Answers (1)

xIsra
xIsra

Reputation: 915

The schema of the files isn't right

files: {
  type: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'File'
  }],
  required: true
}

Or without required:

files: [{
  type: mongoose.Schema.Types.ObjectId,
  ref: 'File'
}]

Read more on the topic of Populate in mongoose: https://mongoosejs.com/docs/populate.html

Upvotes: 3

Related Questions