Sails.js sails中的Create方法生成新记录,但返回错误的请求

Sails.js sails中的Create方法生成新记录,但返回错误的请求,sails.js,sails-mongo,Sails.js,Sails Mongo,我有一个叫做服务的模型 /** * Services.js * * @description :: A model definition represents a database table/collection. * @docs :: https://sailsjs.com/docs/concepts/models-and-orm/models */ module.exports = { attributes: { // ╔═╗╦═╗╦╔╦╗╦╔╦

我有一个叫做服务的模型

/**
 * Services.js
 *
 * @description :: A model definition represents a database table/collection.
 * @docs        :: https://sailsjs.com/docs/concepts/models-and-orm/models
 */

module.exports = {

  attributes: {

    //  ╔═╗╦═╗╦╔╦╗╦╔╦╗╦╦  ╦╔═╗╔═╗
    //  ╠═╝╠╦╝║║║║║ ║ ║╚╗╔╝║╣ ╚═╗
    //  ╩  ╩╚═╩╩ ╩╩ ╩ ╩ ╚╝ ╚═╝╚═╝
    nameService: {
      type: "string",
      required: true,
      description: "Full representation of the service's name.",
      example: "Details of this particular service offered by the studio"
    },
    creditCost: {
      type: "number",
      required: true,
      description: "The number of credits required for this service",
      example: 2
    },
    creditsEarned: {
      type: "number",
      defaultsTo:0,
      description: "The number of credits required for this service",
      example: 200
    },
    price: {
      type: 'number',
      required: true,
      description:"The original price of this service",
      example:1500
    },
    rating: {
      type: 'number',
      defaultsTo:0,
      min: 0,
      max: 5,
    },



    //  ╔═╗╔╦╗╔╗ ╔═╗╔╦╗╔═╗
    //  ║╣ ║║║╠╩╗║╣  ║║╚═╗
    //  ╚═╝╩ ╩╚═╝╚═╝═╩╝╚═╝


    //  ╔═╗╔═╗╔═╗╔═╗╔═╗╦╔═╗╔╦╗╦╔═╗╔╗╔╔═╗
    //  ╠═╣╚═╗╚═╗║ ║║  ║╠═╣ ║ ║║ ║║║║╚═╗
    //  ╩ ╩╚═╝╚═╝╚═╝╚═╝╩╩ ╩ ╩ ╩╚═╝╝╚╝╚═╝


    studioId:{
      model:"Studios"
    },
    bookedServices:{
      collection: 'BookedServices',
      via: 'serviceId'

    },


    timings:{
      collection: 'Timings',
      via: 'serviceId'
    }

  },

};
这是我添加服务的操作文件

由于某些原因,wait Services.create不工作,并且由于未定义serviceRecord,它将返回此badRequest错误。但是当我转向使用promissions时,这里是exec,我看到正在创建记录,但是exec中的第二个参数result也没有定义

由于我必须将studioId推送到服务中,我别无选择,只能在制作记录时将其包括在内,尽管这也显示了badRequest,但它正在将记录放入数据库中

如果有人能告诉我问题的原因,我将不胜感激。我检查了我输入到服务模型中的参数类型,它们确实匹配,serviceName是string,creditCost和price是number

/**
 * studiosControllers/services/addServices.js
 *
 * @description :: Login action for studios.
 * @help        :: See https://sailsjs.com/docs/concepts/actions
 */

module.exports = {
  friendlyName: "Add Services",

  description: "Studios adding services.",

  extendedDescription: `This action will do the part of adding services to the particular studio.`,

  inputs: {
    nameService: {
      type: "string",
      required: true,
      description: "Full representation of the service's name.",
      example: "We are a great studio that offer variety of services..."
    },
    creditCost: {
      type: "number",
      required: true,
      description: "The number of credits required for this service",
      example: 2
    },

    price: {
      type: "number",
      required: true,
      description: "The original price of this service",
      example: 1500
    }
  },

  exits: {
    success: {
      description: "New service was created successfully."
    },

    invalid: {
      responseType: "badRequest",
      description: "Some of the provided details are invalid.",
      extendedDescription:
        "If this request was sent from a graphical user interface, the request " +
        "parameters should have been validated/coerced _before_ they were sent."
    }
  },

  fn: async function(inputs, exits) {
    var { nameService, creditCost, price } = inputs;
    console.log(typeof nameService);
    console.log(typeof creditCost);
    console.log(typeof price);

    let newNameService = nameService.toLowerCase();
    var serviceRecord;

    Services.create({ nameService: newNameService, creditCost:creditCost, price:price,studioId:this.req.params.studioId }).exec(
      function(err,result) {
        if (err) {
          return this.res.send(err);
        }
        console.log(err);
        serviceRecord=result;
        console.log(serviceRecord);
      }
    );

    // try {
    //   serviceRecord = await Services.create({
    //     nameService: newNameService,
    //     creditCost,
    //     price
    //   });
    //   sails.log.info(serviceRecord);
    // } catch (err) {
    //   switch (err.name) {
    //     case "UsageError":
    //       return this.res.badRequest(err);
    //     default:
    //       throw err;
    //   }
    // }

    // If there was info mismatch, throw invalid error
    if (!serviceRecord) {
      throw "invalid";
    }

    let id = this.req.studioId;
    var studioRecord;

    try {
      studioRecord = await Studios.findOne({
        id
      });
      studioRecord.services.add(serviceRecord);
      studioRecord.save();
      return exits.success({
        message: "Service added successfully to the studio",
        data: serviceRecord
      });
    } catch (err) {
      switch (err.name) {
        case "UsageError":
          return this.res.badRequest(err);
        default:
          throw err;
      }
    }
  }
};
编辑:-

这是另一个称为计时的api,即使这样也有同样的问题。是我在创建新文档的过程中犯了什么错误还是其他什么错误

计时模式:-

/**
 * Timings.js
 *
 * @description :: A model definition represents a database table/collection.
 * @docs        :: https://sailsjs.com/docs/concepts/models-and-orm/models
 */

module.exports = {
  attributes: {
    //  ╔═╗╦═╗╦╔╦╗╦╔╦╗╦╦  ╦╔═╗╔═╗
    //  ╠═╝╠╦╝║║║║║ ║ ║╚╗╔╝║╣ ╚═╗
    //  ╩  ╩╚═╩╩ ╩╩ ╩ ╩ ╚╝ ╚═╝╚═╝


    eventInTime: {
      type: "ref",
      required: true,
      columnType: "datetime",
      description: "The date of the event starting",
      extendedDescription: `To store a date, make a date object with 
      'let date=new Date(year, month, day, hours, minutes, seconds, milliseconds)' 
      and then stringify it with 'JSON.stringify(date)' and then store it in the database 

      Send in "stringify" ed version of the date object to this input
      `
    },
    eventOutTime: {
      type: "ref",
      required: true,
      columnType: "datetime",
      description: "The date of the event ending",
      extendedDescription: `To store a date, make a date object with 
      'let date=new Date(year, month, day, hours, minutes, seconds, milliseconds)' 
      and then stringify it with 'JSON.stringify(date)' and then store it in the database 

      Send in "stringify" ed version of the date object to this input
      `
    },
    numberOfSlotsAvailable: {
      type: "number",
      required: true,
      description: "The number of available slots",
      example: 15
    },


    //  ╔═╗╔╦╗╔╗ ╔═╗╔╦╗╔═╗
    //  ║╣ ║║║╠╩╗║╣  ║║╚═╗
    //  ╚═╝╩ ╩╚═╝╚═╝═╩╝╚═╝

    //  ╔═╗╔═╗╔═╗╔═╗╔═╗╦╔═╗╔╦╗╦╔═╗╔╗╔╔═╗
    //  ╠═╣╚═╗╚═╗║ ║║  ║╠═╣ ║ ║║ ║║║║╚═╗
    //  ╩ ╩╚═╝╚═╝╚═╝╚═╝╩╩ ╩ ╩ ╩╚═╝╝╚╝╚═╝

    bookedServicesId:{
      model:"BookedServices"
    },
    serviceId:{
      model:"Services"
    }
  }
};
定时控制器:-

/**
 timingsController/entrance/add-timings.js
 *
 * @description :: Action for adding timings to services.
 * @help        :: See https://sailsjs.com/docs/concepts/actions
 * FIXME: 
 */

module.exports = {
  friendlyName: "Add timings",

  description: "Studi`os adding timings for their services.",

  extendedDescription: `This action will do the part of adding timings to the particular service.`,

  inputs: {
    eventInTime: {
      type: "ref",
      required: true,
      columnType: "datetime",
      description: "The date of the event starting",
      extendedDescription: `To store a date, make a date object with 
      'let date=new Date(year, month, day, hours, minutes, seconds, milliseconds)' 
      and then stringify it with 'JSON.stringify(date)' and then store it in the database 

      Send in "stringify" ed version of the date object to this input
      `
    },
    eventOutTime: {
      type: "ref",
      required: true,
      columnType: "datetime",
      description: "The date of the event ending",
      extendedDescription: `To store a date, make a date object with 
      'let date=new Date(year, month, day, hours, minutes, seconds, milliseconds)' 
      and then stringify it with 'JSON.stringify(date)' and then store it in the database 

      Send in "stringify" ed version of the date object to this input
      `
    },
    numberOfSlotsAvailable: {
      type: "number",
      required: true,
      description: "The number of available slots",
      example: 15
    }
  },

  exits: {
    success: {
      description: "New timing record was created successfully."
    },

    invalid: {
      responseType: "badRequest",
      description: "Some of the provided details are invalid.",
      extendedDescription:
        "If this request was sent from a graphical user interface, the request " +
        "parameters should have been validated/coerced _before_ they were sent."
    }
  },

  fn: async function(inputs, exits) {
    var moment = require("moment");

    var { eventInTime,eventOutTime, numberOfSlotsAvailable } = inputs;


    // var eventInTimeMix = moment(eventInTime);
    // var eventInTimeDate = eventInTimeMix.utc().format("DD-MM-YYYY HH:mm a");
    // console.log(`This is eventInTimeMix: ${eventInTimeMix}`)
    // console.log(`This is eventInTimeDate: ${eventInTimeDate}`)

    // var eventOutTimeMix = moment(eventOutTime);
    // var eventOutTimeDate = eventOutTimeMix.utc().format("DD-MM-YYYY HH:mm a");



    var timingRecord;
    let serviceId = this.req.params.serviceId;
    console.log(serviceId)

  //   timingRecord=await Timings.create({
  //     eventInTimeDate,
  //     eventOutTimeDate,
  //     numberOfSlotsAvailable,
  //     serviceId
  //   }).fetch()

  // console.log(timingRecord)

    Timings.create({eventInTime,
      eventOutTime,
      numberOfSlotsAvailable,
      serviceId})

    .exec(function(err, result) {
      // if (err) {
      //   return this.res.send({err});
      // }
      // return this.res.status(200).send({ message: "Service added successfully" });
      console.log(`This is the error ${err}`);
      console.log(`This is the result ${result}`);

    });

    // try {
    //  timingRecord=await Timings.create({
    //   eventInTimeDate,
    //   eventOutTimeDate,
    //   numberOfSlotsAvailable,
    //   serviceId
    // })
    // } catch (err) {
    //   switch (err.name) {
    //     case "UsageError":
    //       return this.res.badRequest(err);
    //     default:
    //       throw err;
    //   }
    // }

    //FIXME: Remove the ommenting from the below line for verification

    // If there was info mismatch, throw invalid error
    if (!timingRecord) {
      throw "invalid";
    }



  }
};
在控制器中,由于某种原因,控制台日志错误和结果语句返回未定义

我能做些什么来解决这个问题?非常感谢您的帮助。

如中所述,如果您想要新创建记录的副本,您需要链接
.fetch()
方法或
.meta({fetch:true})

类似于以下内容的内容可以做到这一点:

let servicecord=wait Services.create({
nameService:newNameService,
信用成本,
价格
}).fetch();
sails.log.info(服务记录);
如中所述,如果需要新创建记录的副本,则需要链接
.fetch()
方法或
.meta({fetch:true})

类似于以下内容的内容可以做到这一点:

let servicecord=wait Services.create({
nameService:newNameService,
信用成本,
价格
}).fetch();
sails.log.info(服务记录);

在新版Sails中,您需要添加
.fetch()
以在使用
时发回记录。create()

示例来自:


在新版本的Sails中,您需要添加
.fetch()
,以便在使用
.create()

示例来自:


不,这还是不行。另外,我已经使用了exec,它返回结果和err,但由于某种原因,我得到的结果是未定义的。甚至这也说明了同样的事情。但是它返回相同的错误请求,但将文件添加到数据库中。不,这仍然不起作用。另外,我已经使用了exec,它返回结果和err,但由于某种原因,我得到的结果是未定义的。甚至这也说明了同样的事情。但它返回相同的错误请求,但将文件添加到数据库中。您是如何遇到承诺不起作用的?如果您遇到错误,请同时提及。我正在通过邮递员发送请求,它显示的错误是badRequest,如果在出口中定义了(!studioRecord){throw“invalid”;}invalid,则会在此行触发,它应该只在记录没有创建时触发,这意味着创建不起作用,但稍后当我检查数据库时,文档被创建,这是一个谜。但这不仅发生在电影制片厂,也发生在服务业。我尝试删除所有的节点包并安装它们,但没有成功。我正在查看是否错误地使用了create方法,但我觉得一切都很好。您是如何遇到承诺不起作用的?如果您遇到错误,请同时提及。我正在通过邮递员发送请求,它显示的错误是badRequest,如果在出口中定义了(!studioRecord){throw“invalid”;}invalid,则会在此行触发,它应该只在记录没有创建时触发,这意味着创建不起作用,但稍后当我检查数据库时,文档被创建,这是一个谜。但这不仅发生在电影制片厂,也发生在服务业。我尝试删除所有的节点包并安装它们,但没有成功。我正在查看是否使用了错误的创建方法,但对我来说一切都很好
var newUser = await User.create({ fullName: 'Alice McBailey' }).fetch();