简体   繁体   English

Mongoose查找并创建多维数组

[英]Mongoose find and create multidimensional arrays

I'm trying to get the userid, and the array object that contains the specific location within locations. 我正在尝试获取userid,以及包含位置内特定位置的数组对象。

What I want to accomplish is the following: 我想要完成的是以下内容:

The query will return the array location's result. 查询将返回数组位置的结果。

If not userid exist at all, create it, then return the array of the matching location. 如果根本不存在userid,则创建它,然后返回匹配位置的数组。

If the location id Number is not there. 如果位置ID号不存在。 create a new one, then return the array of the matching location. 创建一个新的,然后返回匹配位置的数组。

How can I accomplish this? 我怎么能做到这一点?

Current query: 当前查询:

 easyCrime.findOne({
        userid: userid,
        "locations.location": location
    }, {"locations.$.location": 1}).then(function (err, stats) {


        }

    });

model: 模型:

   userid: {
        type: String,
        default: '57c1c0f3b6b20c011242bf22'
    },
    locations: [
        {
            userid: {
                type: String,
                default: '57c1c0f3b6b20c011242bf22'
            },
            location: {
                type: Number,
                default: 1
            },
            easycrime: [
                {
                    optioname : {
                        type: String,
                        default: 'unknown'
                    },
                    chance: {
                        type: Number,
                        default: 500
                    }
                }
            ],
            heavycrime: [
                {
                    optioname : {
                        type: String,
                        default: 'unknown'
                    },
                    chance: {
                        type: Number,
                        default: 500
                    }
                }
            ],


        }
    ],

    timesteal: {
        type:Number,
        default: 0
    }

I presume that easyCrime is Model, cause there is no such thing as findOne query in a Document. 我认为easyCrime是Model,因为在Document中没有findOne查询这样的东西。 If it is a Model please name it EasyCrime. 如果是型号,请将其命名为EasyCrime。



I had a really hard time interpreting your question. 我很难解释你的问题。 Base on what I understand, this is your solution 根据我的理解,这是您的解决方案

 EasyCrime .findOne({ userid: param.userid}) .exec((err, crime) => { //userid not exists at all, create new if (!crime) { let newCrime = new EasyCrime({...}); newCrime.save(...); return; } //Check if location exists for (let i = 0; i < crime.locations.length; ++i) { if (crime.locations[i].location === param.location) { //crime.location[i] is what you're finding return; } } //Cannot find any location with provided param.location crime.locations.push({ userid: ..., location: param.location, ... }); crime.save(...); }) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM