[英]Mongoose - findOneAndUpdate dynamically $push into array
I am trying to dynamically add new values into an array field.我正在尝试将新值动态添加到数组字段中。
Been making enough progress lately to not have to bother asking them on here although this is one question I thought should indeed be asked: So to start it off here's my schema:最近取得了足够的进展,不必费心在这里问他们,尽管这是我认为确实应该问的一个问题:所以从这里开始是我的模式:
var ugh = new mongoose.Schema({
yes: String,
bio: String,
keys: [{
nickname: String,
data1: String,
data2: Boolean,
data3: String,
data4: String,
}]
});
var ughhh = mongoose.model('X', ugh, 'x');
and here is the resolver I am trying to write to solve:这是我试图编写的解析器:
setSomething: async (root, { nickname, data1, data2, data3, data4 }, { userId }) => {
if (nickname) {
let action = await ughhh.findOneAndUpdate(
{ _id: userId },
{ $set:
{
'keys.0.nickname': nickname,
'keys.0.data1': data1,
'keys.0.data2': data2,
'keys.0.data3': data3,
'keys.0.data4': data4,
},
},
{
new: true,
upsert: true,
});
action;
}
return null;
},
},
Now I do like the numerical sorting of newly set keys, starting with 0.现在我确实喜欢新设置的键的数字排序,从 0 开始。
But when I try to $set
another, it replaces the value instead of adding the new entry into the array!但是当我尝试$set
另一个时,它会替换值而不是将新条目添加到数组中!
How can I add new entries into the array instead of replacing the current value and I prefer adding new entries with unique ID or key for future reference如何将新条目添加到数组中而不是替换当前值,我更喜欢添加具有唯一 ID 或键的新条目以供将来参考
you can just push into the array field like:您可以像这样推入数组字段:
{ $push:
keys: {
'nickname': nickname,
'data1': data1,
'data2': data2,
'data3': data3,
'data4': data4
}
}
note that when you push new items into the array, it would generate an unique '_id' field which is useful for future reference请注意,当您将新项目推送到数组中时,它会生成一个唯一的“_id”字段,以供将来参考
{ $push: {
keys: {
nickname: nickname,
data1: data1,
data2: data2,
data3: data3,
data4: data4,
}
}
},
indeed solved the issue:)确实解决了这个问题:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.