Nodejs Mongoose 查询时怎么返回指定的列呢?

Nodejs Mongoose 查询时怎么返回指定的列呢?

查询时间段里面的数据:

Model.find({create_at: {$gte: bdate, $lte: edate}}, function(err, data){
    ……
}

想要返回指定的列,该怎么做呢?

3 回复

当然可以!在使用 Mongoose 进行查询时,你可以通过 select 方法来指定返回哪些字段。以下是一个详细的示例代码,解释如何在查询时返回指定的列。

示例代码

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// 定义一个简单的数据模型
const UserSchema = new Schema({
    name: String,
    email: String,
    password: String,
    create_at: Date
});

const User = mongoose.model('User', UserSchema);

// 假设我们有一个开始日期和结束日期
const bdate = new Date('2023-10-01T00:00:00Z');
const edate = new Date('2023-10-31T23:59:59Z');

// 查询特定时间段内的数据,并指定返回的字段
User.find(
    { create_at: { $gte: bdate, $lte: edate } },
    // 指定返回的字段
    { name: 1, email: 1, _id: 0 },
    function (err, data) {
        if (err) {
            console.error(err);
            return;
        }
        console.log(data);
    }
);

解释

  1. 定义数据模型

    • 我们首先定义了一个 User 数据模型,包含 name, email, password, 和 create_at 字段。
  2. 设置查询条件

    • 使用 find 方法进行查询。
    • 查询条件是 create_at 在指定的时间段内 ($gte 表示大于等于,$lte 表示小于等于)。
  3. 指定返回的字段

    • 第二个参数是一个对象,用于指定返回哪些字段。
      • { name: 1, email: 1 } 表示只返回 nameemail 字段(值为 1 表示包含该字段)。
      • { _id: 0 } 表示不返回默认的 _id 字段(值为 0 表示排除该字段)。
  4. 回调函数

    • 查询结果会通过回调函数返回,如果查询成功,data 参数将包含匹配的数据。

这样,你就可以通过 select 方法来灵活地控制返回的字段了。希望这个示例对你有帮助!


傻了一下,哈哈,官网网站有例子:

var Person = db.model('Person', yourSchema);

// find each person with a last name matching ‘Ghost’, selecting the name and occupation fields Person.findOne({ ‘name.last’: ‘Ghost’ }, ‘name occupation’, function (err, person) { if (err) return handleError(err); console.log(’%s %s is a %s.’, person.name.first, person.name.last, person.occupation) // Space
Ghost is a talk show host. })

‘name occupation’ 就是指定要返回的字段

在使用 Mongoose 进行查询时,你可以通过 select 方法来指定需要返回的字段。如果你希望在查询中排除某些默认返回的字段(例如 _id),或者只返回特定的几个字段,可以使用 select 方法。

示例代码

假设我们有一个用户模型 User,定义如下:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
    username: String,
    email: String,
    password: String,
    createdAt: { type: Date, default: Date.now }
});

const User = mongoose.model('User', userSchema);

现在我们想查询 emailusername 字段,而不是返回所有字段。可以这样写:

User.find({ create_at: { $gte: bdate, $lte: edate } })
    .select('email username') // 返回 email 和 username 字段
    .exec(function(err, users) {
        if (err) {
            console.error('Error fetching users:', err);
            return;
        }
        console.log(users);
    });

如果你希望排除某些字段(例如 _id),可以这样做:

User.find({ create_at: { $gte: bdate, $lte: edate } })
    .select('-_id') // 排除 _id 字段
    .exec(function(err, users) {
        if (err) {
            console.error('Error fetching users:', err);
            return;
        }
        console.log(users);
    });

如果想同时包含和排除某些字段,你可以这样组合使用:

User.find({ create_at: { $gte: bdate, $lte: edate } })
    .select('email username -_id') // 返回 email 和 username 字段,并排除 _id 字段
    .exec(function(err, users) {
        if (err) {
            console.error('Error fetching users:', err);
            return;
        }
        console.log(users);
    });

解释

  • .select() 方法用于指定查询结果中需要包含或排除哪些字段。
  • 字符串 'email username' 表示只返回 emailusername 字段。
  • 字符串 '-_id' 表示排除 _id 字段。
  • 你可以将多个选择条件组合在一起,用空格分隔。

这样你就可以根据需求灵活地控制查询返回的字段了。

回到顶部