【发布时间】:2020-07-26 03:30:39
【问题描述】:
我在更新 mongoose 架构中的 mixed type 字段时遇到问题。这不是最好的架构设置
但我有理由这样设置它。现在我要执行javascript array-like
push 等操作。我想访问在嵌套数组中迭代的当前文档的索引,在tags
场地。像这样:
猫鼬模式
let user = {
name : String,
email : String,
tags : []
}
tags 字段是在创建用户时动态生成的,我最终得到了这样的结果
将用户插入数据库后
tags : [
[{obj1}, {obj2}, {obj3}, ...],
[...],
[...],
[...],
[...]
]
我想要实现的 - 以“javascript方式”将新文档推送到嵌套数组
user.tags[0].forEach(obj, index){
// Do some operations here with obj and index
// I don't know how to update a nested array with the mongo $push operator that is why I am falling back to the `js array push` method
let newObj = { foo: bar }
user.tags[0].push(newObj)
user.save()
}
用postman测试后显示操作成功并返回 一个插入的项目,但我观察到两个问题:
- 对 db 不持久,但同时我对 postman 的回复如下:
{
name : bar,
email : foo,
tags : [
[{ foo : bar}], // from the last push operation I did
[],
[],
[]...
...
]
}
- 对任何数组索引(例如第 0 个索引)的后续
push操作替换当前对象而不是附加它:user.tags[0].push(obj)===> 这替换了第一个对象(当然是在邮递员响应中,而不是 db,因为它似乎不是持久的)
任何帮助如何实现这一点将不胜感激
我只是在学习这些东西,非常欢迎任何更好的方法来解决同样的问题,谢谢。 :)
【问题讨论】:
-
你能用例子指定你想要达到的最终输出吗?
标签: javascript arrays mongodb express mongoose