猫鼬-将对象ID推送到ObjectId数组

时间:2020-10-22 07:24:56

标签: javascript node.js mongoose

根据以下架构:

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

我创建了一个文件文档,我试图获取其ID并将其推入文件数组。这是我已经尝试过的方法(不起作用):

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

我还检查了file._id是否不是null / undefined,并且那里有一个ObjectId:

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

如何将文件ID插入文件数组?

编辑:运行此命令后,我看到了数据库,并且看到ObjectId推送了该数组,但我不能在输出中看到它。

我该如何解决?

1 个答案:

答案 0 :(得分:2)

文件的架构不正确

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

或者不需要:

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

详细了解猫鼬填充主题:https://mongoosejs.com/docs/populate.html

相关问题