[英]update an array field in the document in mongodb using nodejs
我的模特:
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);
}
}
);
};
您的代碼確實需要重構:
// 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');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.