gpt4 book ai didi

node.js - 如何在 sails js 中一次使用对象参数请求保存多个数据

转载 作者:太空宇宙 更新时间:2023-11-04 00:41:36 24 4
gpt4 key购买 nike

目前,我正在使用 sails js + mongoDB 为移动应用程序开发 API。我想保存从移动应用程序发送的多个数据,并通过 Controller 函数中的 req 参数(作为对象)捕获它。

我的 Controller 代码的某些部分如下所示:

var contactData = req.allParams().Contact;
looping.. {
Contact.create(contactData[index]).exec(function addContact(err,createdContact){ });
}

您能告诉我如何实现循环以将多个联系人数据保存到数据库中的最佳方法吗?

问候,argi danu。

最佳答案

好吧,如果您知道请求参数的“name”属性,那么您可以简单地使用 create 方法 -

var contactData = req.allParams();
var name = contactData.name // attribute name
var number = contactData.number // attribute name

然后只需调用 create 方法

Contact.create({name : name, number :number}).exec(functionaddContact(err,createdContact){ 

// DO Something
});

但是如果您严格希望使用 for 循环从请求参数中获取所有数据,那么请考虑以下场景 -

通过将 contactData 附加到 [ ] 中,将 req 参数的组合转换为 JSON 对象

   var json = '[' + contactData +']';

然后使用以下代码从创建的 JSON 对象中获取参数值,如下所示

 for (var property in obj) {

if (obj.hasOwnProperty(property)) {

if(typeof obj[property] === 'string') {

console.log(property); // provides the property name
console.log(obj[property]); // provides the value of the property
}
}

也许这会有所帮助。它适用于 SQL 数据库

关于node.js - 如何在 sails js 中一次使用对象参数请求保存多个数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36498358/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com