我的模特:
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');
关于arrays - 使用nodejs在mongodb中更新文档中的数组字段,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49357701/