4

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?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.