arrays - Mongoose Model, cleaning/parsing an Array efficiently
问题描述
I am having some issues with a mongoose array, it's likely due to my lacking understanding of the library, and I can't find the exact answer I'm looking for in the docs.
For starters I have my schema and model declarations:
const gConfig = new Schema({ aList: Array, maxChanLimit: Number }), globalConfiguration = mongoose.model('globalConfig', gConfig);
And I have my command which fetches the array, parses out _id, then pushes the new item to the array, and overwrites the existing one in the database.
if((message.author.id === g.ownerID) && (g.id.toString() === tocGuild) && message.content.startsWith("!updatealist"))
{
let mc = message.content.replace("!updatealist ", "");
globalConfiguration.findOneAndUpdate({},{$push: {"aList":mc }}, { upsert: true }, function(err, data) {
if (err) return console.log(err);
var str = JSON.stringify(data); str = str.replace(RegExp(/"_id"|"__v"|'/g),""); var arr = str.split(`","`);
});
}
I feel like there has to be a better way to do this, I've tried something like this based on what I've read:
globalConfiguration.findOneAndUpdate({},{$push: {"-_id aList":mc }}
However this did not remove _id from the array. I suppose how I'm doing it is a way to do it, but I know it isn't efficient, and isn't dynamic at all, it's also extremely bulky in terms of code and could be streamlined using the library.
In practice, what is the best way to properly read an array from a model with Mongoose? How do you read from the array without the additional objects Mongoose adds by default? What is the best way to add an item to an existing model?
Any help is appreciated, thank you.
解决方案
如果您想更好地控制更新过程,您可以这样做,在 mongoose 文档中建议您可以先查询要更新的项目/文档,一旦查询到该文档并在那里,您可以进行更改到它,比如它包含一个数组,你可以推送到它或从中弹出或其他任何东西..
它在你的控制
所以,
if((message.author.id === g.ownerID) && (g.id.toString() === tocGuild) && message.content.startsWith("!updatealist"))
{
let mc = message.content.replace("!updatealist ", "");
globalConfiguration.findOne({"your query"}, function(err, data) {
if (err) throw (err);
data.array.push("something");
data.save();// save it again with updates
var str = JSON.stringify(data); str = str.replace(RegExp(/"_id"|"__v"|'/g),""); var arr = str.split(`","`);
});
}
推荐阅读
- symfony4 - 如何获取扩展类的ObjectManager
- java - 如何使用 Java 编辑文件名
- regex - 匹配在 golang 中始终用逗号或空格分隔的重复模式
- azure - Unable to assign public ip address to AKS: pending forever
- java - 如何在生产者中发送 java 对象作为值
? - django - ListView中如何根据ForeignKey的主键创建动态过滤器?
- python - Django 无法导入任何包:AttributeError: __name__
- javascript - 从 ag-grid 自定义渲染器更新 React 组件的状态
- android - 导航组件生命周期
- python-3.x - websocket的握手源代码中的laddr和raddr是什么