Javascript Mongoose-将对象id推送到ObjectID数组
根据以下模式:Javascript Mongoose-将对象id推送到ObjectID数组,javascript,node.js,mongoose,Javascript,Node.js,Mongoose,根据以下模式: const mongoose=require('mongoose')) var schema=newmongoose.schema({ 用户:{ 类型:mongoose.Schema.Types.ObjectId, ref:'用户', 独一无二:没错, 必填项:true }, 档案:{ 类型:[mongoose.Schema.Types.ObjectId], ref:'文件', 必填项:true } },{时间戳:true}) module.exports=mongoose.mo
const mongoose=require('mongoose'))
var schema=newmongoose.schema({
用户:{
类型:mongoose.Schema.Types.ObjectId,
ref:'用户',
独一无二:没错,
必填项:true
},
档案:{
类型:[mongoose.Schema.Types.ObjectId],
ref:'文件',
必填项:true
}
},{时间戳:true})
module.exports=mongoose.model('model',schema);
我创建了一个文件文档,并尝试获取其ID并将其推送到文件数组。以下是我已经尝试过的(不起作用):
Model.findOneAndUpdate(
{user:user.\u id},
{$push:{files:file.\u id}},
{upsert:true,new:true,runValidators:true}
)
我还检查了文件。\u id
不是空的/未定义的,并且那里有一个ObjectId:
{
“模型”:{
“文件”:[],
“_id”:“5f90c117624d199c9c7984af”,
“用户”:“5f31d5fe37d233f359d82f5a”,
“_v”:0,
“createdAt”:“2020-10-21T23:15:35.025Z”,
“更新日期”:“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'
}]
阅读有关在猫鼬中填充主题的更多信息: