【问题标题】:Not getting _id from new record没有从新记录中获取 _id
【发布时间】:2019-09-14 04:33:17
【问题描述】:

我有一个使用 node、express 和 mongoose 的 api。当我使用 Postman 调用 api 时,会返回模型中的 _id 值。当我使用基于 angularjs 和 ionic 构建的 Web 应用程序调用 api 时,_id 为空。在这两种情况下都会保存记录。

我尝试在 angularjs 服务中设置标题。如果获取所有记录,则 ID 会返回。我已经尝试从猫鼬模型和角度模型中设置和删除_id

// api method 
public save = async (req:Request, res:Response): Promise<any> => {
        let newDfr = new DfrModel(req.body);

        try {
            const insertDFR = await newDfr.save({ validateBeforeSave: false}); 

            if (!insertDFR) {
                return res.status(404).send({
                    success: false,
                    message: 'Error Saving DFR',
                    data: null
                  });
            }
            console.log (newDfr);
            res.status(200).send({
                success: true,
                data: insertDFR
              });

        } catch (err) {
            res.status(500).send({
                success: false,
                message: err.toString(),
                data: null
            });
        }
    }


// Service Method on Service Class 
 public saveDFR(dfrModel: DfrModel) {
    return this.httpClient.post(environment.apiURL + '/dfrs', dfrModel);
  }

// Method on component
  async onSaveForm() {
    if (this.form.value.dfrStatus == null) {
      this.form.value.dfrStatus = 'Open';
    }

    const loader = await this.loadingController.create({
      message: 'Saving DFR, one moment please.',
      animated: true
    }).then(loaderElement => {
      loaderElement.present();

      this.dfrService.saveDFR(this.form.value).subscribe( val => {
        loaderElement.remove();
        this.dfrService.showNotification('DFR Template Saved');
      }, error => {
        loaderElement.remove();
        this.showAlert('Error Saving DFR. Please ensure all fields are valid');
      });
    });
  }

//客户端模型

export class DfrModel {
    constructor (
        public _id: string,
        public projectName: string,
        public projectNumber: string,

    ){}


}

【问题讨论】:

    标签: angularjs mongoose save


    【解决方案1】:

    由于我发送的是 form.value,因此附加了一个值为 null 的 _id 键。 _id 也附加到我的模型上。在 mongodb 中保存新文档时,该 _id 不应出现在有效负载中。因此,我只是删除了正在提交的 _id 键/值对。

    这似乎是处理这种情况的一种奇怪方式,我认为我的某些设置不正确。如果有人对提交新文件有更好的解决方案,请在下面发表评论。谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-03
      • 2012-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-31
      • 2013-06-14
      • 1970-01-01
      相关资源
      最近更新 更多