gpt4 book ai didi

javascript - 用 Mongoose 插入子数组

转载 作者:可可西里 更新时间:2023-11-01 09:14:24 27 4
gpt4 key购买 nike

我有一个具有三个深度级别的数据模型。

var job = mongoose.Schema({
id:Number,
jobName:String
});

var demo = mongoose.Schema({

id:Number,
demoName:String,
job:[job]
});

var ExerciseSchema = mongoose.Schema({

id:Number,
name:String,
area:String,
medicalObj:[demo]
});

var Exercise = mongoose.model('Exercise', ExerciseSchema);

我想把新对象压入第二个嵌套数组

我正在尝试这种方式,但不起作用:

    Exercise.update({'area':area},{$push:{"medicalObj.job":{jobName:'Andrea'}}},{upsert:true},function(err){

if(err){
console.log("ERROR" + err);
}else{
console.log("Successfully");

}
});

最佳答案

有一件事我想指出:medicalObj 将是一个对象数组。我想你会想要将 jobName: andrea 添加到包含在作业中的特定数组中,所以这就是我在测试中所做的:

Exercise.findOne({area: area}, function(e,r){
r.medicalObj.forEach(function(demo){
// the following line looks for the specific array to add jobName Andrea to.
if (demo.demoName == "test") {
demo.job.push({jobName: "Andrea"});
r.save(function(err, res){
console.log(err, res);
});
});
});

如果你只想插入 jobName: "Andrea"如果它不存在,你可以很容易地添加一个支票:

Exercise.findOne({area: area}, function(e,r){
r.medicalObj.forEach(function(demo){
if (demo.demoName == "test") {
var found = false;
demo.job.forEach(function(jobs){
if (jobs.jobName == "Andrea") found == true;
});
if (found == false) {
demo.job.push({jobName: "Andrea"});
r.save(function(err, res){
console.log(err, res);
});
};
};
});
});

关于javascript - 用 Mongoose 插入子数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19314421/

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