使用mongoose

时间:2016-05-13 06:48:35

标签: arrays node.js mongodb mongoose mean

我正在尝试开发一个MEAN应用程序,我能够从前端到后端服务器发送数据,我能够在mongoose架构中推送数组数据,但我无法逐个推送数组中的对象元素。我的服务器代码看起来像

 router.post('/', function(req, res) {
      console.log(req.body.details);//getting data in array
     console.log(req.body.academics);//getting data in array
     console.log(req.body.trainings);////getting data in *object*
     var detail = req.body.details;
     console.log(detail.city); // i can get data here 
     var register = new recruit(req.body);

register.contact.push({
    city: detail.city || "",//but the data doesnot get inserted now
    state: detail.state || "",
    municipalityVdc: detail.municipalityVdc || "",
    wardNo: detail.wardNo || "",
    houseNo: detail.houseNo || "",
    streetName: detail.streetName || "",
    contactNo: detail.contactNo || "",
    eContactNo: detail.eContactNo || "",
    email: detail.email || "",
    aEmail: detail.aEmail || "",
    facebookId: detail.facebookId || "",
    linkedinId: detail.linkedinId || ""
});
register.qualification.push(req.body.academics);// array of data are inserted inside the mongoose schema
register.trainings.push(req.body.trainings);// data get inserted

可以立即保存所有数据,但我正在尝试管理不同阵列中的数据。我还有另一个数组要插入细节

  register.basicDetails.push({
    firstName: detail.firstName || "",//no data are inserted here too
    lastName: detail.lastName || "",
    fathersName: detail.fathersName || "",
    dob: detail.dob || "",
    marritalStatus: detail.marritalStatus || "",
    drivingLicense: detail.drivingLicense || "",
    vehicle: detail.vehicle || "",
    gender: detail.gender || "",
    photo: req.file.originalname || "",
    jobTitle: detail.jobTitle || "",
    experiance: detail.experiance || ""
});
register.save(function(err, respond) {
    if (err) {
        throw err;
    } else {
        res.json(respond);
    }
})

}); module.exports = router;

如果我创建mongoose模块的对象并直接将其保存到数据库但只插入数组而不是对象,我的代码可以工作, 我的工作代码看起来像

 router.post('/', function(req, res) {

var register = new recruit(req.body);

register.save(function(err, respond) {
    if (err) {
        throw err;
    } else {
        res.json(respond);
    }
   })
 });
 module.exports = router;
有些人请赐教我使用mongoose管理数据,并纠正我错在哪里。非常感谢任何回应。

1 个答案:

答案 0 :(得分:0)

我认为对你有所帮助

获取客户端数据对象与您的mongoose招募架构字段相同,然后只保存所有数据

例如

这是用户方案

var UserSchema= new mongoose.Schema({

name:{type:String},
dateCreated:{type:String},
place:[{
    city:{type:String},
    state:{type:String}
}]

});

这是客户端数据(req.body)

{ "name":"test","dateCreated":"date","place":[{"city":"chennai","state":"tamil"}]}

保存功能

var newUser = new  User(data)
newUser.save(function(err, respond) {
if (err) {
    throw err;
} else {
    res.json(respond);
}})});

输出

{ place:
    [ { _id: 5737548a96d6deb40b321a53,
        state: 'tamil',
        city: 'chennai' } ],
    _id: 5737548a96d6deb40b321a52,
    dateCreated: 'date' }