【问题标题】:Creating new ObjectId using ``mongoose.Schema.Types.ObjectId`` is not working使用“mongoose.Schema.Types.ObjectId”创建新的 ObjectId 不起作用
【发布时间】:2021-12-31 07:39:36
【问题描述】:

我创建了 mongoose Schema 并将 studentId 字段类型添加为 studentId: {type: mongoose.Schema.Types.ObjectId, ref: 'Student'}, 填充该集合的目的。

填充部分已完成,并且工作正常。但是当我创建一个新文档(在 studentClass 中)时,我将studentId 字段作为String 发送,因此我必须尝试将String 转换为ObjectId,如下所示,

const studentObjectId = mongoose.Schema.Types.ObjectId(studentId);

使用上述方法对我不起作用。也不会触发任何错误。似乎没有在该行之后编译代码。

我也将猫鼬导入为const mongoose = require('mongoose');

studentClass型号如下,

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const studentClassModel = new Schema({
    studentId: {type: mongoose.Schema.Types.ObjectId, ref: 'Student'},
    groupId: {type: String}
});

module.exports = mongoose.model('StudentClass', studentClassModel, 'STUDENT_CLASS')

【问题讨论】:

    标签: node.js mongodb mongoose populate objectid


    【解决方案1】:

    mongoose.Schema.Types 用于声明架构。

    mongoose.Types 用于构造这些类型。

    使用

    const studentObjectId = mongoose.Types.ObjectId(studentId);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-30
      • 1970-01-01
      • 1970-01-01
      • 2011-05-17
      • 2018-12-31
      • 1970-01-01
      • 2016-07-24
      • 2014-11-21
      相关资源
      最近更新 更多