【发布时间】: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