Javascript 更新和插入数据嵌套数组,最多4级
我有一个这样的模式Javascript 更新和插入数据嵌套数组,最多4级,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我有一个这样的模式 var continent = new mongoose.Schema({ continent: { type:string, }, country: [{ country: { type: String, }, currency: { type: String, }, state: [{
var continent = new mongoose.Schema({
continent: {
type:string,
},
country: [{
country: {
type: String,
},
currency: {
type: String,
},
state: [{
state_name: {
type: string,
},
company:[{
location:{
type:string,
},
loc_type:{
type:string,
},
employee:[{
emp_name:{
type:string
},
emp_age:{
type:Number,
}
}]
}]
}]
}]
})
我必须在公司内部推动价值,员工也要更新个人价值
我试过这个密码
var data_push = {
loc_type:"urban",
location:"india",
}
var continent = await Line_data.update(
{continent_name:continent_name, 'continent.country_name':country_name,'continent.country_name.state_name':state_name },
{ "$push": { "country.$.state_name.company": data_push} }
)
我在3层和4层面对问题。
谁能帮我解决这个问题 您可以使用MongoDB运算符和option的组合来实现所需的功能
var data_push = {
loc_type:"urban",
location:"india",
}
Line_data.update(
{
continent: continent_name,
},
{
$push: {
'country.$[countryElement].state.$[stateElement].company': data_push,
}
},
{
arrayFilters: [
{
'countryElement.country': country_name,
},
{
'stateElement.state': state_name,
}
]
}
)
如果您想更深入,例如添加员工,该怎么办?这与上面的方法基本相同,只需扩展elementMatches和ArrayFilter:
Line_data.update(
{
continent: continent_name,
},
{
$push: {
'country.$[countryElement].state.$[stateElement].company.$[companyElement].employee.$[employeeElement]': employee_data,
}
},
{
arrayFilters: [
{ 'countryElement.country': country_name },
{ 'stateElement.state': state_name },
{ 'companyElement.location': company_location },
{ 'employeeElement.emp_name': employee_name }
]
}
)
谢谢你的帮助,如果我想在employee collection中添加数据,我相信employee collection是指嵌套在company字段中的employee数组。这几乎是相同的方法,您只需要扩展元素匹配和数组过滤器。我将更新答案,以包含一个场景,即如果您要添加员工文档。