node.js 猫鼬中的“$in”有什么问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11839765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:08:02  来源:igfitidea点击:

What's wrong with "$in" in mongoose

node.jsmongoose

提问by Roman

Good day for everyone. I have a strange error working with mongoose

每个人都有美好的一天。我在使用猫鼬时遇到了一个奇怪的错误

module.js:437
  var compiledWrapper = runInThisContext(wrapper, filename, tru
                        ^
SyntaxError: Unexpected token .
    at Module._compile (module.js:437:25)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:362:17)
    at require (module.js:378:17)
    at Object.<anonymous> (E:\Dropbox\Dropbox\FCP\server.js
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)

I gues it's goes from

我猜它来自

dbQueries.remove({_id: {$in: {req.body.data}}, authorId: req.user._id}, function onRemoveSomething(err){
            if(err) {
                res.json({epicFail: 'ERR_RestrictedAccess'});
                return; 
            }
        });

So, I have no idea what is wrong.

所以,我不知道出了什么问题。

回答by Andy Ray

$intakes an array, not an invalidly formatted javascript object

$in接受一个数组,而不是一个格式无效的 javascript 对象

{_id: {$in: [req.body.data]}

or if req.body.datais already an array, omit the wrapping []

或者如果req.body.data已经是一个数组,省略包装[]

回答by Haneef Abdulla

you have to check req.body.datais an array or not, see the code below {_id: {$in: _.isArray(req.body.data) ? req.body.data : [req.body.data] } //const _ = require('lodash');

您必须检查req.body.data是否为数组,请参阅下面的代码 {_id: {$in: _.isArray(req.body.data) ? req.body.data : [req.body.data] } //const _ = require('lodash');

回答by Lucky Soni

Build your query based on the data

根据数据构建查询

var match = {
    authorId: req.user._id
};

if(Array.isArray(data)) {
    match._id = {$in: data};
} else {
   match._id = data;
}

dbQueries.remove(match, function findMyDocs(err, foundDocs) {

});