繁体   English   中英

Mongoose查找并创建多维数组

[英]Mongoose find and create multidimensional arrays

我正在尝试获取userid,以及包含位置内特定位置的数组对象。

我想要完成的是以下内容:

查询将返回数组位置的结果。

如果根本不存在userid,则创建它,然后返回匹配位置的数组。

如果位置ID号不存在。 创建一个新的,然后返回匹配位置的数组。

我怎么能做到这一点?

当前查询:

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


        }

    });

模型:

   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
    }

我认为easyCrime是Model,因为在Document中没有findOne查询这样的东西。 如果是型号,请将其命名为EasyCrime。



我很难解释你的问题。 根据我的理解,这是您的解决方案

 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