gpt4 book ai didi

arrays - 使用nodejs更新mongodb文档中的数组字段

转载 作者:太空宇宙 更新时间:2023-11-04 01:51:46 25 4
gpt4 key购买 nike

我的模型:

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 编写了如下 Controller 代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com