【问题标题】:Mongoose Select Method Not Working As ExpectedMongoose Select 方法未按预期工作
【发布时间】:2021-09-22 01:38:00
【问题描述】:

试图在架构中简单地包含一个选择设置为 false 的字段。由于某种原因,用 select 方法覆盖它不起作用。排除其他字段有效,但包含无效。在以下示例中,我尝试包含“active_account”字段。什么可能导致这种行为?

架构

const Schema = new mongoose.Schema({
    active_account: {
        type: Boolean,
        default: true,
        select: false
    }
})

功能

exports.deactivate_user = async ( req , res , next ) => {
    
    const user = await User.findByIdAndUpdate( req.params.id , { active_account: false } ).select( '+active_account' );
    
    res.status( 200 ).json({
        status: 'Success',
        data: user
    });
};

【问题讨论】:

    标签: javascript mongoose mongoose-schema


    【解决方案1】:

    根据docs;

    A.findByIdAndUpdate(id, update, options) // 返回查询

    所以,

     const user = await User.findByIdAndUpdate( 
                                               req.params.id, //id
                                               { active_account: false }, //update
                                               { select: 'active_account', new: true } //options
                                              );
    

    设置new = true获取更新版本的数据。

    【讨论】:

    • 你说的有道理,但它不适用于更改。即使我在前面添加“+”以指定包含,您的特定代码也不会返回任何内容。带有“+*”的快速通配符测试仍然不包括 active_account 字段。对此非常困惑。
    • 添加“-”将删除一个不同的字段。
    • 包括 + 为我工作,像这样const demo = await Demo.findByIdAndUpdate( objects[1]._id, //id { active_account: false }, //update { select: "+active_account", new: true } //options );
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    • 1970-01-01
    • 2019-04-22
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多