繁体   English   中英

Mongoose - 将对象 id 推送到 ObjectIds 数组

[英]Mongoose - push object id to array of ObjectIds

根据下面的架构:

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 插入到 files 数组中?

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

我该如何解决?

文件的架构不正确

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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