使用mongoose更新mongoDb中数组内部的对象 [英] Update object inside the array in mongoDb using mongoose

查看:85
本文介绍了使用mongoose更新mongoDb中数组内部的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MongoDB来更新位于MongoDB集合中数组内部的更新对象值.

I am working on MongoDB for update object value which is inside of the array in MongoDB collection.

我的收藏就像

{
  "_id": ObjectId("59b7e839200a5c00ee2d2851"),
  "player": "New",
  "playesList": [
    {
      "_id": ObjectId("59b2a4f749fee40959e556d3"),
      "name": "abcd",
    },
    {
      "_id": ObjectId("59b2a4f749fee40959e556d4"),
      "name": "pqrs",
    }
  ]
}

现在,我想更新ID为59b2a4f749fee40959e556d3的玩家的名字(我的意思是第一个玩家的名字是abcd),其收藏ID为59b7e839200a5c00ee2d2851和玩家New.

Now I want to update the name of the player whose id is 59b2a4f749fee40959e556d3(i mean first player name currently it was abcd), whose collection id is 59b7e839200a5c00ee2d2851 and player New.

所以我正在尝试使用此查询进行更新

So I am trying to update with this query

play.update(
      {
          '_id': '59b7e839200a5c00ee2d2851',
          'player': 'new',
          'playesList._id': '59b2a4f749fee40959e556d3'
      },
      {
          '$set': { 'playesList.$.name': 'wxyz' }
      },
      function(error, success) {
         console.log(error, success);
      }
)

但是在这里,我进入了null { ok: 1, nModified: 0, n: 0 }这样的控制台,并且值无法更新到集合中. 请帮助我如何解决此错误. 预先谢谢你.

But here I got in console like null { ok: 1, nModified: 0, n: 0 } and value cann't update into collection. Please help me how can solve this error. Thank you in advance.

推荐答案

MongoDB集合中数组内部的对象(文档)称为- 子文档

Objects (documents) inside the array in MongoDB collection are called - subdocuments

在这种情况下,要使用其自己的_id更新特定子文档,可以使用Mongoose

In this case, to update specific subdocument with its own _id, you can use Mongoose findOneAndUpdate method:

play.findOneAndUpdate({
    "_id": "59b7e839200a5c00ee2d2851",
    "playesList._id": "59b2a4f749fee40959e556d3"
}, {
    "$set": {
        "playesList.$.name": "something"
    }
}, function(error, success) {

})

首先,您需要使用以下命令在集合中查找文档:

first you are need to find document in collection with:

"_id": "59b7e839200a5c00ee2d2851"

然后使用第二个参数通过其_id查找子文档:

then find subdocument by its _id using second parameter:

"playesList._id": "59b2a4f749fee40959e556d3"

,当您找到要更新的子文档时,请使用 $设置运算符以将新值设置为找到的子文档的name属性:

and when you find the subdocument that you want to update, use $set operator to set new value to name property of found subdocument:

"$set": {
    "playesList.$.name": "something"
}

请注意,findOneAndUpdate返回更新文档的先前状态.

Note that findOneAndUpdate returns previous state of updated document.

工作示例:

var express = require('express')
var app = express()
var router = require('express').Router()
var mongoose = require('mongoose')
var Schema = mongoose.Schema

mongoose.connect('mongodb://localhost:27017/stackoverflowanswer')
mongoose.Promise = global.Promise

var PlayerSchema = new Schema({
    play: String,
    playersList: [{
        name: String
    }]
})

var Player = mongoose.model('Players', PlayerSchema)

app.use('/', router)

router.get('/add-player', function(req, res, next) {
    var player = new Player()

    player._id = "59b7e839200a5c00ee2d2851"
    player.play = "New"
    player.playersList.push({
        _id: "59b2a4f749fee40959e556d3",
        name: "abcd"
    }, {
        _id: "59b2a4f749fee40959e556d4",
        name: "pqrs"
    })

    player.save(function(err) {
        if (err) throw err

        res.json({
            message: 'Success'
        })
    })
})

router.get('/update-player', function(req, res, next) {
    Player.findOneAndUpdate({
        "_id": "59b7e839200a5c00ee2d2851",
        "playersList._id": "59b2a4f749fee40959e556d3"
    }, {
        "$set": {
            "playersList.$.name": "wxyz"
        }
    }, function(error, success) {
        if (error) throw error

        res.json({
            message: 'Success'
        })
    })
})

app.listen(8080, function() {
    console.log('Node.js listening on port ' + 8080)
})

这篇关于使用mongoose更新mongoDb中数组内部的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆