Node.js猫鼬.update与ArrayFilters [英] Node.js Mongoose .update with ArrayFilters

查看:86
本文介绍了Node.js猫鼬.update与ArrayFilters的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就目前而言,我可以使用Mongo shell来使该功能正常工作,但是使用Mongoose可以解决Node.js内部嵌套数组的问题.

As it stands, I am able to get this functionality working using the Mongo shell, but having issues with the nested arrays inside of Node.js using Mongoose.

成功的Mongo Shell命令:

Mongo shell command that is successful:

db.test.update({}, {$set: {"this.$[i].that.$[x].amnt": 10000}}, {arrayFilters: [{"i._id": ObjectId('5a568059bc44142a9ca33d09')}, {"x.userId": ObjectId('5a466acb864c752f8c9890c6')}]})

结果:将amnt字段更改为10000.在从数据库中提取的给定字符串上调用ObjectId('')之前,没有返回任何匹配项.

Result: changed the amnt field to 10000. There was no matches returned until calling ObjectId('') on the given strings pulled from the database.

Node.js代码:

Node.js code:

var conditions = {}
var update = {$set: {"this.$[i].that.$[x].amnt": 1000}
var options = {arrayFilters: [{"i._id": weekId}, {"x.userId":  r.userId}]}

myModel.update(conditions, update, options, function(err, rowsAffected){
    // handler 
}

结果:{ok:0,n:0,nModified:0}

Result: { ok: 0, n: 0, nModified: 0 }

_id和userId是模型的架构中的schema.Types.ObjectId.

_id and userId are schema.Types.ObjectId in the schema for the model.

我尝试用3.6.1的最新文件更新node_modules/mongodb.看来猫鼬使用3.0.1.打印到控制台上的typeof(weekId)或typeof(r.userId)显示字符串的类型.我相信这会根据架构而改变,但是无论哪种方式,我都尝试在这些项目上调用mongoose.Types.ObjectId(weekId)来查看是否可以解决此问题,但是没有运气.

I tried updating the node_modules/mongodb with the latest files for 3.6.1. It appears mongoose uses 3.0.1. Printing out to console typeof(weekId) or typeof(r.userId) shows type of string. I believe this gets changed based on the schema, but either way I tried calling mongoose.Types.ObjectId(weekId) on these items to see if this resolved it, but no luck.

MongoDB:3.6.1 猫鼬:5.0.0-rc2

MongoDB: 3.6.1 Mongoose: 5.0.0-rc2

推荐答案

我不知道Mongoose 5.0.0是否应该支持开箱即用的Arrayfilters,但是您可以使用直接执行的Mongoose的命令方法来实现因此,可以使用MongoDB上的所有功能,包括MongoDB 3.6.1上的ArrayFilters

I don't know if Mongoose 5.0.0 is supposed to support Arrayfilters out of the box but you can achieve it by using Mongoose's command-method which directly executes on MongoDB, hence can utilize all features available which includes ArrayFilters on MongoDB 3.6.1

示例:

mongoose.connection.db.command({
  update: <YourModel>.collection.name,
  updates: [
    {
      q: { 'field1.field2._id': mongoose.Types.ObjectId(<someObjectid>) },
      u: {
        $set: { 'field1.$.field2.$[field].fieldToUpdate': "updated!" },
      },
      arrayFilters: [
        { 'field._id': mongoose.Types.ObjectId(<someObjectid>) },
      ],
    },
  ],
})

这篇关于Node.js猫鼬.update与ArrayFilters的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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