【问题标题】:Inserting Data to MongoDb using Nodejs使用 Nodejs 将数据插入到 MongoDb
【发布时间】:2020-04-15 23:11:03
【问题描述】:

我的 Mongodb 中有几个对象,其中一个对象的集合示例是:

_id: xxxxxxxxxxxxxxxxxxxx
abcd:
    efgh: " "

其中abcd 是一个包含efgh 数组的对象,我想将数据推送到数组efgh 中(这意味着在触发api 时将数据添加到该特定_id 和efgh 中)

我为此写了一个 api

app.put('/route/:id', function(req, res, next){
    //console.log(req.params.id)
    console.log(req);
    collection.findByIdAndUpdate({abcd:req.params.id}, req.body.abcd).then(function(collection){
        res.send(collection)
    })
})

但是当我在邮递员中尝试它时它不起作用,你能帮我解决这个问题吗?

【问题讨论】:

  • 请检查条件 { _id: "5db6b26730f133b65dbbe459" }
  • @MaheshBhatnagar 我检查过但没用
  • {abcd:req.params.id} 错误条件,请告诉什么是响应?
  • @MaheshBhatnagar UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "{ abcd: '5db6b26730f133b65dbbe459' }" at path "_id" for model "collection" at new CastError
  • {_id:ObjectId("5db6b26730f133b65dbbe459") } 使用objectId关键字

标签: node.js database mongodb rest


【解决方案1】:

您的第二个参数必须使用 $set 并且第一个参数必须与 id 匹配:

collection
  .findByIdAndUpdate(req.params.id, {$set: { abcd: req.body.abcd })
  .then(function(collection) {
    res.send(collection);
  });

【讨论】:

    【解决方案2】:

    如果你想在数组中推送,MongoDB 提供了 $push 或 $addToSet。

    collection.findByIdAndUpdate({_id :req.params.id}, {$addToSet: { "abcd.efgh": req.body.abcd.efgh } }).then(function(collection){
        res.send(collection)
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-25
      • 2019-11-03
      • 1970-01-01
      • 2014-06-29
      • 2021-02-13
      • 1970-01-01
      相关资源
      最近更新 更多