【问题标题】:Why can't I use '0' as an _id with mongoDB and mongoose?为什么我不能在 mongoDB 和 mongoose 中使用 '0' 作为 _id?
【发布时间】:2021-05-21 06:14:08
【问题描述】:

我有一组代表文件夹的对象。我想让用户根据需要创建文件夹,并限制应用程序将创建一个“根”文件夹(对象),并且我想控制这个文件夹的 _id 属性。根据mongoDB documentation,我应该可以设置 _id 字段,但是当我尝试时出现错误:

Cast to ObjectId failed for value "0" at path "_id"

mongo 文档说 _id 可以是数组以外的任何 BSON data type,所以我不明白为什么“0”无效。为什么我不能使用 '0' 作为 _id?

明确地说,我希望 mongoDB 为根文件夹以外的所有其他情况生成一个 id。

文件夹架构:

const mongoose = require('mongoose');
const constants = require('../config/constants');

const { Schema } = mongoose;

const FolderSchema = new Schema(
  {
    user: {
      type: Schema.Types.ObjectId,
      ref: 'User',
      required: [true, 'Folder must have a user'],
    },
    name: {
      type: String,
      required: true,
      trim: true,
    },
    dateCreated: {
      type: Date,
      default: Date.now,
    },
    lastUpdated: {
      type: Date,
      default: Date.now,
    },
    parentId: {
      type: String,
      required: true,
    },
  },
  {
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  },
);

FolderSchema.index({ name: 'text' });

// eslint-disable-next-line func-names
FolderSchema.virtual('id').get(function () {
  return this._id.toHexString();
});

module.exports = mongoose.model('Folder', FolderSchema);

【问题讨论】:

  • 您能否包含模型的架构?
  • @caffeinated.tech 完成

标签: node.js mongodb mongoose


【解决方案1】:

您需要在架构中声明_id 应具有的格式。 Mongoose 默认为 BSON ObjectId,但可以根据the docs 覆盖它:(强调我的)

你也可以用你自己的 _id 覆盖 Mongoose 的默认 _id。请注意:Mongoose 将拒绝保存没有 _id 的文档,因此,如果您定义自己的 _id 路径,则您有责任设置 _id。

const schema = new Schema({ _id: Number }); const Model = mongoose.model('Test', schema);

const doc = new Model(); await doc.save(); // Throws "document must have an _id before saving"

doc._id = 1; await doc.save(); // works

将此应用于您的架构:

const FolderSchema = new Schema(
  {
    _id: {
      type: Number,
      required: true,
    },
    user: {
      type: Schema.Types.ObjectId,
      ref: 'User',
      required: [true, 'Folder must have a user'],
    },
    name: {
      type: String,
      required: true,
      trim: true,
    },
    dateCreated: {
      type: Date,
      default: Date.now,
    },
    lastUpdated: {
      type: Date,
      default: Date.now,
    },
    parentId: {
      type: String,
      required: true,
    },
  },
  {
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  },
);

【讨论】:

  • 感谢您的解决方案。我相信我想做的事情可能是不可能的。我只想为每个用户指定 1 个文件夹(即根文件夹)的 _id,并让 mongoDB 为所有其他用户生成它。现在我想了想,如果用户文件夹一起存储在同一个数据库中,那将行不通,因为需要有多个 id 为 0 的文件夹。也许在我的模型上拥有另一个属性会更好,比如布尔值'isRoot'。我想这必须是尝试操纵 id 的标准方法。
  • @regexAgainstTheMachine 是的,布尔方法更常见。您不希望一个字段具有多种类型,因为从长远来看它只会导致错误。
  • 听起来不错。我接受了您的回答,因为这是覆盖 _id 字段的正确方法。再次感谢。
猜你喜欢
  • 2019-03-12
  • 2019-03-10
  • 1970-01-01
  • 2015-04-24
  • 2022-06-16
  • 2011-10-15
  • 2015-02-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多