我目前的架构如下:
positionsApplied:[{
position_id:String,
index_position: Number
}],
我还有3个对象需要插入到我的数据库中:
如何通过Ajax调用将这些插入到我的数据库中?到目前为止我尝试了什么:
将数据添加到这样的数组中:
["58d6b7e11e793c9a506ffe8f", 0, "58c2871414cd3d209abf4fc1", 1, "58d6b7e11e793c9a506ffe7f", 1]
然后会通过我的ajax调用传递哪个?(不确定)
$.ajax({
url: "/insertPositionIndex",
type: "POST",
dataType: "json",
data: {
newarray
},
success: function (data) {
console.log(data);
}
})
插入数据库是我遇到的问题,如何分解数组才能插入?
app.post('/insertPositionIndex', function(req, res){
var object = req.body.ordered_divs;
console.log(req.body);
User.update(
{ "_id": req.user._id},
{ "$push":
{"positionsApplied":
{
// unsure what to do here?
}
}
}
).exec(function (err, result) {
console.log(result);
res.send({ results: result });
});
});
非常感谢任何帮助! *注意模式中的position_id字段是数组中的div_id,索引位置字段也是数组中的index_pos。
用户架构:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = new Schema({
id: String,
name: String,
companyname: String,
password: String,
email: String,
username: String,
location: String,
role:String,
teamwork:Number,
initiative:Number,
technical_skills: Number,
communication:Number,
employees: String,
profile_image: String,
biodescription: String,
twitter: String,
facebook: String,
instagram: String,
linkedin: String,
biodescription: String,
positionsApplied:[{
position_id:String,
index_position: Number
}],
experience: [{
title: String,
location: String,
company: String,
start: String,
end:String,
description:String
}],
position: [{
_id:String,
title: String,
location: String,
start: String,
term:Number,
description:String,
date: {type: Date, default: Date.now},
applied:[{
candidate_id: String,
profile_image: String,
location: String,
name: String,
_id:String
}],
}],
education: [{
school: String,
location: String,
degree: String,
start: String,
end:String,
description:String,
_id:String
}],
images: [{
one: String,
two: String,
three: String,
four: String,
five:String,
six:String
}],
});
module.exports = mongoose.model('User', User);
答案 0 :(得分:0)
由于你的Schema是一个对象数组,你得到的数据(根据浏览器的控制台)也是一个对象数组,为什么你不能自己传递该数组(控制台中的数据)浏览器)通过ajax并使用mongodb $each
的{{1}}将其保存到数据库中。
$push
您必须更改$.ajax({
url: "/insertPositionIndex",
type: "POST",
dataType: "json",
data: {
arrayOfObjects
},
success: function (data) {
console.log(data);
}
})
app.post('/insertPositionIndex', function(req, res){
var object = req.body.ordered_divs;
console.log(req.body);
User.update(
{ "_id": req.user._id},
{
"$push":
{
"positionsApplied":{
$each: req.body.arrayOfObjects
}
}
}
).exec(function (err, result) {
console.log(result);
res.send({ results: result });
});
});
密钥以匹配架构arrayOfObjects
密钥。