【问题标题】:Mongoose how to insert element on existing objects (MongoDB and Node.js)Mongoose 如何在现有对象(MongoDB 和 Node.js)上插入元素
【发布时间】:2017-10-22 05:38:54
【问题描述】:

在我的模型中,我有这样的东西:

subjects: {
    Mathematics: {
      questionsanswered: [
        "x+2=3, solve for x please",
        "How do you write an expression that represents all quadrantal angles?"
      ],
      questionsasked: [
        "how to convert sin to cos?",
        "factor the trinomial: 3x^2+7x+2"
      ]
    }
}

如您所见,有很多子元素,我完全是 Mongoose 和 Node.js 的初学者,我正在尝试在 questionsanswered 数组字段中添加另一个问题(字符串)。我查看了文档并尝试了

userModel.update({username: username},{$pushAll: { subjects:{Mathematics:{questionsasked:['what is the definition of calculus']}}}},{upsert:true},function(err){
                if(err){
                        console.debug(err);
                }else{
                        console.debug("Successfully added");
                }
        });

但是它说'Modifier $pushAll allowed for arrays only',有谁知道如何在questionsanswered 数组中插入另一个元素?非常感谢!

【问题讨论】:

  • 试试$pushAll: {"subjects.Mathematics.questionsasked": "what is the definition of calculus"}
  • 它仍然说同样的话:S
  • Nvm,我得到它使用 {"subjects.Mathematics.questionsasked": ["what is the definition of calculus"]} 只需要添加 ' [ ] ' 非常感谢!跨度>

标签: javascript node.js mongodb express mongoose


【解决方案1】:

$pushAll 现已弃用。

要向现有数组添加一个元素,只需使用$push

userModel.update({ username }, { $push: {
  'subjects.Mathematics.questionsasked': 'value'
}});

若不存在则添加元素使用addToSet:

userModel.update({ username }, { $addToSet: {
  'subjects.Mathematics.questionsasked': 'unique value'
}});

要添加多个元素,请使用$each:

userModel.update({ username }, { $push: {
  'subjects.Mathematics.questionsasked': { $each: ['value1', 'value2'] }
}});

【讨论】:

    猜你喜欢
    • 2012-02-07
    • 1970-01-01
    • 2016-11-05
    • 2012-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    相关资源
    最近更新 更多