根据以下模式:
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
是否为空/未定义,并且那里有一个ObjectId:
{
"model": {
"files": [],
"_id": "5f90c117624d199c9c7984af",
"user": "5f31d5fe37d233f359d82f5a",
"__v": 0,
"createdAt": "2020-10-21T23:15:35.025Z",
"updatedAt": "2020-10-22T07:16:53.843Z"
}
}
如何将文件的ID插入到文件数组中?
EDIT:运行此命令后,我看到了DB,并看到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