我想编辑我的Api以便能够填充引用的架构。 这是我的架构:
export const taskSchema = new Schema ({
user:{
type: String,
required: true
},
project: {
type: String,
required: true
},
issue: {
type: String,
required: true
},
title: {
type: String,
required: true
},
records : [{
_domain: {
type: Schema.Types.ObjectId,
ref: 'TaskDomains'
},
time: {
type:Number
}
}],
dateCreated: {
type: Date,
default: Date.now
}
});
我的taskDomain模式:
export const TaskDomains = new Schema ({
label:{
type: String,
required: true
}
});
如何编辑以下post方法以填充引用的TaskDomain模式。 这是我的方法:
import * as mongoose from 'mongoose';
import {taskSchema,TaskDomains} from '../models/tasks.model';
import {Request, Response} from 'express';
const Task = mongoose.model('Task', taskSchema);
const domain = mongoose.model('domain', TaskDomains);
export class taskController{
public addNewTask (req: Request, res:Response){
let newTask = new Task();
newTask.user = req.body.user;
newTask.project = req.body.project;
newTask.issue = req.body.issue;
newTask.title = req.body.title;
newTask.dateCreated = req.body.dateCreated;
newTask.records = new domain(req.body._domain);
newTask.records = new domain(req.body._domain.label);
newTask.records = req.body.time;
newTask.save((err, task)=>{
if(err){
res.send(err);
}
res.json(task);
});
}
}
答案 0 :(得分:1)
您当前的方法有些错误,您需要先保存域文档,然后成功保存就可以创建任务文档。
尝试一下:
public addNewTask (req: Request, res:Response){
// create the domain document first, before creating the task document, and then store its _id in the task document
let _domain = new domain(req.body._domain);
_domain.save((err,_domain)=>{
let newTask = new Task();
newTask.user = req.body.user;
newTask.project = req.body.project;
newTask.issue = req.body.issue;
newTask.title = req.body.title;
newTask.dateCreated = req.body.dateCreated;
// here you only need to store the _id of the newly created _domain document
newTask.records = [{
_domain : _domain._id,
time : req.body.time
}]
newTask.save((err, task)=>{
if(err){
res.send(err);
}
//if you want populated _domain object in your records array, you can use .populate()
Task.populate(task,{path : records._domain},(err,task) =>
{
res.json(task);
})
});
})
}
我假设,您的请求正文如下:
{
user : "user_name",
project : "project_name",
issue : "issue_name",
title : "title_",
dateCreated : "date",
_domain : {
label : "some_label"
},
time : 12345
}