首页 > 解决方案 > 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.

标签: arraysnode.jsmongodbmongoose

解决方案


如果您想更好地控制更新过程,您可以这样做,在 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(`","`);
        });
}

推荐阅读