Here is My Model, I am trying to save the data in the Tools array of the Model.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var toolSchema = new Schema({
name: {type: String},
tools: [{
jira: {
url: {type: String},
userName: {type: String},
passWord: {type: String},
status: {type: Boolean, default: false}
},
test1: {
token: {type: String},
uri: {type: String}
},
test2: {
uri: {type: String}
},
test3: {
uri: {type: String}
}
}]
});
module.exports = mongoose.model('Tool', toolSchema);
Here is My code to save the Data
var Tools = require("../models/tool");
exports.create = function (req, res) {
var toolArr = req.body.tools;
console.log(toolArr);
var apps = new Tools();
toolArr.forEach(function (item, index) {
if (item.jira) {
console.log(item.jira.userName);
apps.tools.jira.userName = item.jira.userName;
apps.save(function (err, result) {
if (err) {
console.log('Error in saving the Devops: ' + err);
throw err;
}
else {
console.log(result);
res.send(result);
}
});
}
})
};
I am not able to save the data in mongodb i am Getting Error, can any body help me on this. i am sending the data using postman Like this.
tools[0][jira][userName]:Developer
Error located -> apps.tools.jira.userName = ...
according to your schema, tools
is an array and doesn't have a .jira
. You probably want to to do apps.tools[index].jira.userName = ...
. Also I'd recommend not running an apps.save()
inside your .forEach()
since that'll make multiple writes to your db, but I don't know your exact use case.
If the req.body.tools
contains the array of objects like the schema format
var apps = new Tools();
apps.tools = req.body.tools;
apps.save(function(err,result){
if (err) {
console.log('Error in saving the Devops: ' + err);
throw err;
} else {
res.send(result);
}
});
Example of sending your data from postman
{
"name":"abc",
"tools":[
{
"jira":{
"url":"www.abc.com",
"userName":"abvc",
"password":"123"
},
"test1":{
"token":"your token",
"uri":"www.anything.com"
}
}
]
}
And then save your data by this code
var Tools = require("../models/tool");
var apps = new Tools();
var data=req.body /* assuming it as a post request and data is send in body */
apps(data).save(function(err,result){
if(err){
throw err;
}else {
res.send(result);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.