Mongoose查找并创建多维数组

mar*_*ria 7 javascript arrays mongoose mongodb node.js

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

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

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

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

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

我怎么能做到这一点?

当前查询:

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


        }

    });
Run Code Online (Sandbox Code Playgroud)

模型:

   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
    }
Run Code Online (Sandbox Code Playgroud)

roc*_*cer 1

我认为 easyCrime 是模型,因为文档中没有 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(...);
    })
Run Code Online (Sandbox Code Playgroud)