How to exclude one particular field from a collection in Mongoose?

前端 未结 6 2133
逝去的感伤
逝去的感伤 2020-12-13 12:15

I have a NodeJS application with Mongoose ODM(Mongoose 3.3.1). I want to retrieve all fields except 1 from my collection.For Example: I have a collection Pr

相关标签:
6条回答
  • 2020-12-13 12:30

    You could do this

    const products = await Product.find().select(['-image'])
    
    0 讨论(0)
  • 2020-12-13 12:32

    I don't know where you read about that .exclude function, because I can't find it in any documentation.

    But you can exclude fields by using the second parameter of the find method.

    Here is an example from the official documentation:

    db.inventory.find( { type: 'food' }, { type:0 } )
    

    This operation returns all documents where the value of the type field is food, but does not include the type field in the output.

    0 讨论(0)
  • 2020-12-13 12:38

    Use query.select for field selection in the current (3.x) Mongoose builds.

    Prefix a field name you want to exclude with a -; so in your case:

    Query.select('-Image');
    

    Quick aside: in JavaScript, variables starting with a capital letter should be reserved for constructor functions. So consider renaming Query as query in your code.

    0 讨论(0)
  • 2020-12-13 12:40
    Model.findOne({ _id: Your Id}, { password: 0, name: 0 }, function(err, user){
      // put your code
    });
    

    this code worked in my project. Thanks!! have a nice day.

    0 讨论(0)
  • 2020-12-13 12:43

    I am use this with async await

    async (req, res) => {
          try { 
            await User.findById(req.user,'name email',(err, user) => {
              if(err || !user){
                return res.status(404)
              } else {
                return res.status(200).json({
                  user,
                });
              }
            });
          } catch (error) {
            console.log(error);
          }
    
    0 讨论(0)
  • 2020-12-13 12:50

    In the updated version of Mongoose you can use it in this way as below to get selected fields.

    user.findById({_id: req.body.id}, 'username phno address').then(response => {
      res.status(200).json({
        result: true,
        details: response
      });
    }).catch(err => {
      res.status(500).json({ result: false });
    });
    
    0 讨论(0)
提交回复
热议问题