【问题标题】:Mongoosejs updating a subdocumentMongoosejs 更新子文档
【发布时间】:2020-06-30 18:47:10
【问题描述】:

我正在尝试使用 $set 运算符推送子文档位置。我见过类似的 SO 线程 Mongoose find/update subdocument。我的模型如下所示。

const mongoose = require('mongoose');

const positionSchema = new mongoose.Schema({

    posA: {
        type: Number,
    },

    posB: {
        type: Number,
    },

    date: {
        type: Date,
        default: Date.now
    }

}, { _id: false });

const LocationSchema = new mongoose.Schema({

    position: [positionSchema],

    username: {
        type: String,
        required: true
    },

}, { versionKey: false });

const Location = mongoose.model('Location', LocationSchema);

module.exports = Location;

第一次在数据库中创建文档。

{
    "_id":{"$oid":"5e737eb7f0bdd67cf7521f6b"},
    "username":"username",
    "position":[{
        "posA":{"$numberInt":"123.855"},
        "posB":{"$numberInt":"45.8777"},
        "date":{"$date":{"$numberLong":"1584627688055"}}
    }]
}

为了更新子文档,我使用了这个

const newPos = { posA: 76.66665, posB: 109.4455567 };

Location.findOneAndUpdate(
    { username: username},    // filter
    {
        "$set": {
            "position.$": newPos      // the new position added to the array
        }
    },
    (err, result) => {
        if (err) throw err;
        console.log(result);
});

虽然,我收到一个错误并且子文档没有添加到数组中

MongoError: 位置运算符没有从查询中找到所需的匹配项。

有不同的方法吗?

【问题讨论】:

  • 你有没有这样尝试过 "$set": { "position": newPos // 添加到数组中的新位置 } 这样的?
  • 并尝试使用 updateOne 代替
  • 用户名在哪里声明?
  • 用户名是从程序的其他部分给出的。我已经尝试过你上面说的解决方案。它更新了我的子文档,但我没有很好地解释。我需要在数组中推送一个新的子文档。我将编辑我的帖子
  • 尝试使用 $push 而不是 $set

标签: node.js mongodb mongoose


【解决方案1】:

为了将项目推送到数组,请尝试使用 $push 而不是 $set

【讨论】:

    【解决方案2】:

    只需在“位置”后去掉'.$',它应该可以工作。

    MongoDb 找不到位置运算符的匹配项,因为您尚未在查询中定义它。

    但在这种情况下您不需要使用位置运算符。

    编辑:另外,如果您不想替换原始数组,请使用:$push 而不是 $set

    【讨论】:

      猜你喜欢
      • 2012-12-07
      • 2017-08-12
      • 2021-03-08
      • 2014-09-20
      • 2016-10-27
      • 2015-06-17
      • 2017-08-10
      • 1970-01-01
      • 2011-08-04
      相关资源
      最近更新 更多