简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM