node.js - Mongoose 不会使用简单的 find() 返回文档中的所有字段

标签 node.js mongodb express mongoose mongodb-query

我有以下架构:

let User = new Schema({
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  firstName: {
    type: String,
    required: false
  },
  lastName: {
    type: String,
    required: false
  },
  templates: {
    type: Schema.Types.ObjectId,
    ref: 'TemplateInstance',
    required: false
  }
},{
  collection: 'users',
  timestamps: true
});

以及以下 Mongoose 代码:

exports.getUsers = (req, res) => {
  User.find((err, users) => {
    if(err)
      return res.status(400).json( { 'users_get_all': 'failure', 'err': err } );
    return res.status(200).json( { 'users_get_all': 'success', 'users': users } );
  });
};

最初,每个用户文档的"template"字段中没有任何内容,因为在用户创建帐户后,他们就可以向其附加模板。我已手动将一些模板 ObjectID 添加到某些用户的"template"字段中,但是当我运行 getUsers() 函数时,会返回用户文档,但没有"template"字段:

{"users_get_all":"success","users":[{"_id":"5b39f9da294d041b58f97cb3","email":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1266776166777f737b7e52777f737b7e3c717d7f" rel="noreferrer noopener nofollow">[email protected]</a>","password":"password","firstName":"firstName","lastName":"lastName","createdAt":"2018-07-02T10:09:30.400Z","updatedAt":"2018-07-02T10:21:34.579Z","__v":0},{"_id":"5b39ff5723d93c17bc00eabf","email":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="35415046415058545c5907755058545c591b565a58" rel="noreferrer noopener nofollow">[email protected]</a>","password":"password","firstName":"firstName2","lastName":"lastName2","createdAt":"2018-07-02T10:32:55.308Z","updatedAt":"2018-07-02T10:32:55.308Z","__v":0}]}

如果我在 Studio 3T 之类的工具中查看 MongoDB,模板数组中肯定有引用 Template 集合中的 Templates 的 ObjectID。

Screenshot of Studio 3T showing Users collection

知道为什么不返回"template"字段吗?

最佳答案

按如下方式更新您的架构:

let User = new Schema({
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  firstName: {
    type: String,
    required: false
  },
  lastName: {
    type: String,
    required: false
  },
  templates: [{
    type: Schema.Types.ObjectId,
    ref: 'TemplateInstance',
    required: false
  }]
},{
  collection: 'users',
  timestamps: true
});

与在数据库中一样,数组中有模板,并且您将其声明为架构中的对象。

关于node.js - Mongoose 不会使用简单的 find() 返回文档中的所有字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51134236/

相关文章:

javascript - 如何转到定义了 Angular 配置的 url 的父级 url

node.js - MongoDB 确保索引不会停止重复

node.js、express 和不同的端口

node.js - crypto.decipher 导致流在 Node js 中无法关闭

javascript - 从 Node.js 中的 Array 对象中删除特定属性

javascript - Mongoose 使用方法将模式添加到模式中

mongodb - 如何获取 mongo 中同一字段的唯一值列表?

java - 如何在构建时将从源代码文件名或内容派生的数据添加到资源

node.js - Node.js 和 Express 的基本模板类似于 Django

node.js - 编辑 req.user 对象