使用nodejs

时间:2018-03-19 07:25:28

标签: arrays node.js mongodb

我的模特:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/sampleapp');
var mongoSchema = mongoose.Schema;
var Schema = mongoose.Schema;
var userprofileSchema = {
      "firstname" : String,
      "lastname"  : String,
      "gender"    : String, 
      "username"  : String,
      "email"     : String,
      "password"  : String,
      "phone"     : Number,
      "dateofbirth": Date,
      "address"   : [],
      "education" : [],
      "workexperience" : [],
      "usercertification" : [],
      "skills" : [],
      "sociallinks" : [],
      "interest"  : [],
      "created_date" : {type : Date, default : Date.now},
      "updated_date" : {type : Date, default : Date.now}  
};

module.exports = mongoose.model(' profiles',userprofileSchema);

我想更新usercertifications数组字段,任何人都可以帮助我。我使用$ set:

编写了如下控制器代码
exports.updateprofile = function(req, res){
Profile.update(
  { '_id': req.body.id },
  { $set:  { 'address.$.city': req.body.city }},
  (err, result) => {
    if (err) {
      res.status(500)
      .json({ error: 'Unable to update competitor.', });
    } else {
      res.status(200)
      .json(result);
    }
 }
);    

};

1 个答案:

答案 0 :(得分:0)

您的代码需要真正重构:

// User.model.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userProfileSchema = new Schema({
      "firstname" : String,
      "lastname"  : String,
      "gender"    : String, 
      "username"  : String,
      "email"     : String,
      "password"  : String,
      "phone"     : Number,
      "dateofbirth": Date,
      "address"   : [String], // define schema, this is my eg. - array of numbers
      "education" : [{ school: String }], // define schema, this is my eg. - array of objects 
      "workexperience" : [], // define schema
      "usercertification" : [], // define schema
      "skills" : [], // define schema
      "sociallinks" : [], // define schema
      "interest"  : [], // define schema
      "created_date" : {type : Date, default : Date.now},
      "updated_date" : {type : Date, default : Date.now}
});

module.exports = mongoose.model('Profile', userProfileSchema);

在主档案或路线

... some requires
const mongoose = require('mongoose');
const Profile = require('..path to User.model.js');
mongoose.connect('mongodb://localhost/sampleapp');