簡體   English   中英

Mongodb:如何通過我的 api 填充我的架構中引用的架構

[英]Mongodb: how to populate a schema referenced in my schema through my api

我想編輯我的 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); }); } }
我需要幫助編輯 post 方法。 我一直在嘗試不同的方法,但都沒有奏效。

您當前的方法有些錯誤,您需要先保存域文檔,然后成功保存才能創建任務文檔。

嘗試這個:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM