【发布时间】:2021-05-24 15:34:07
【问题描述】:
我尝试更新 mongoDB 中的数组对象。当未定义变量 listID 时,它只会更新数组的第一个对象(但这不是我想要的)。
我的目标是添加单词 ID,更新 last_practiced 字段并将单词计数字段的数量增加 wordID 的数量。
我也尝试过聚合,但我无法让它工作。
我当前的查询
Words.prototype.updatePersonalWordLists = async function(userID, listData) {
const listID = listData.list_id
const wordIDs = listData.word_ids
const last_practiced = listData.last_practiced
const numberOfNewWords = listData.word_ids.length
const lists = await personalWordLists.updateOne(
{"user_id": userID, "lists.$.list_id": listID },
{
$addToSet: { "lists.$.practiced_words": { $each: wordIDs}},
$set: {
"lists.$.last_practiced": last_practiced,
$inc: {"lists.$.wordCount": numberOfNewWords}
}
}
)
return lists
}
let userID = "609b974f6bd8dc6019d2f304"
let listData = {
list_id: "609d22188ea8aebac46f9dc3",
last_practiced: "03-04-2021 13:25:10",
word_ids: ["1", "2", "3", "4", "5"],
}
word.updatePersonalWordLists(userID, listData).then(res => console.log(res))
我的计划
const mongoose = require('mongoose');
const personalWordListsSchema = new mongoose.Schema({
user_id: {
type: String
},
lists: Array
});
module.exports = personalWordListsSchema
我希望有人可以帮助我解决这个问题。提前致谢。
【问题讨论】:
-
尝试在过滤器部分省略
$,例如"lists.list_id": listID -
非常感谢,它成功了!你能解释一下为什么会这样吗?不应该是未定义的“lists.list_id”吗?
-
MongoDB 查询语言允许您使用该表示法直接引用数组中对象中的键。
$操作符在更新中用于表示满足过滤条件的数组对象,所以$在查询部分没有特殊含义。 -
好的,知道了!谢谢。
标签: mongodb mongoose aggregation-framework