mongoose 在 express 中使用 _id 链接两个集合,并将 id 作为数字或字符串插入

Posted

技术标签:

【中文标题】mongoose 在 express 中使用 _id 链接两个集合,并将 id 作为数字或字符串插入【英文标题】:mongoose link two collection with _id in express and insert id as number or string 【发布时间】:2021-05-22 18:18:44 【问题描述】:

你好我想首先创建两个集合是房间并且有一些属性和 _id 作为主键或对象 id 我将在 post 方法中插入它,另一个集合是预订并且有一些属性我想存储 id 或对象 id 我将其插入到预订集合的第一个集合中,以将两个集合相互链接并可以填充

 const mongoose=require('mongoose');
const Schema =mongoose.Schema;
const bcrypt=require('bcryptjs');
const  schema  = mongoose.Schema;

 //---------- schema data -------------//
const roomschema=Schema(
     _id:
      type:String ,
      ,
   floor:
       type:String,
        required:true
    ,
    status:
        type:String,
        enum:['booking','busy','free'],
        default:'free'
    ,
    price:
        type:String,
    ,
    bed:
        type:Number
    ,
    offer:
     type:String,
     enum:['yes','no'],
     default:'no',
     
);
const room =mongoose.model('room',roomschema);

const roombooking= Schema(
      _id:
      
        type:Schema.Types.ObjectId,
       ref: 'room' ,
    ,
      bed:
        type:String,
     ,
      price:
          type:String,
          required:true,
      ,
      from:
      type:Date,
      default:Date.now,
      ,
      to:
        type:Date,
        default:Date.now,
        ,
);

const booking =mongoose.model('booking',roombooking);
module.exports=
    room:room,
    booking:booking
;

这是我制作的架构文件,但我有一个错误投射

Error: booking validation failed: _id: Cast to ObjectId failed for value "12" at path "_id"
    at ValidationError.inspect (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\mongoose\lib\error\validation.js:47:26)
    at formatValue (internal/util/inspect.js:725:31)
    at inspect (internal/util/inspect.js:293:10)
    at formatWithOptions (internal/util/inspect.js:1949:40)
    at Object.value (internal/console/constructor.js:301:14)
    at Object.log (internal/console/constructor.js:336:61)
    at C:\Users\DC\Desktop\datapage\hotelapptest\models\controller.js:103:17
    at processTicksAndRejections (internal/process/task_queues.js:97:5) 
  errors: 
    _id: CastError: Cast to ObjectId failed for value "12" at path "_id"
        at ObjectId.cast (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\mongoose\lib\schema\objectid.js:281:11)
        at ObjectId.SchemaType.applySetters (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\mongoose\lib\schematype.js:1091:12)
        at model.$set (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\mongoose\lib\document.js:1269:20)
        at model.$set (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\mongoose\lib\document.js:1013:16)
        at model.Document (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\mongoose\lib\document.js:148:12)
        at model.Model (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\mongoose\lib\model.js:105:12)
        at new model (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\mongoose\lib\model.js:4700:15)
        at booking (C:\Users\DC\Desktop\datapage\hotelapptest\models\controller.js:97:16)
        at Layer.handle [as handle_request] (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\express\lib\router\layer.js:95:5)
        at next (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\express\lib\router\route.js:137:13)
        at Route.dispatch (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\express\lib\router\route.js:112:3)
        at Layer.handle [as handle_request] (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\express\lib\router\layer.js:95:5)
        at C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\express\lib\router\index.js:281:22
        at Function.process_params (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\express\lib\router\index.js:335:12)
        at next (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\express\lib\router\index.js:275:10)
        at Function.handle (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\express\lib\router\index.js:174:3) 
      stringValue: '"12"',
      messageFormat: undefined,
      kind: 'ObjectId',
      value: '12',
      path: '_id',
      reason: Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
          at new ObjectID (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\bson\lib\bson\objectid.js:59:11)
          at castObjectId (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\mongoose\lib\cast\objectid.js:25:12)
          at ObjectId.cast (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\mongoose\lib\schema\objectid.js:279:12)
          at ObjectId.SchemaType.applySetters (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\mongoose\lib\schematype.js:1091:12)
          at model.$set (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\mongoose\lib\document.js:1269:20)
          at model.$set (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\mongoose\lib\document.js:1013:16)
          at model.Document (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\mongoose\lib\document.js:148:12)
          at model.Model (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\mongoose\lib\model.js:105:12)
          at new model (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\mongoose\lib\model.js:4700:15)
          at booking (C:\Users\DC\Desktop\datapage\hotelapptest\models\controller.js:97:16)
          at Layer.handle [as handle_request] (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\express\lib\router\layer.js:95:5)
          at next (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\express\lib\router\route.js:137:13)
          at Route.dispatch (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\express\lib\router\route.js:112:3)
          at Layer.handle [as handle_request] (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\express\lib\router\layer.js:95:5)
          at C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\express\lib\router\index.js:281:22
          at Function.process_params (C:\Users\DC\Desktop\datapage\hotelapptest\node_modules\express\lib\router\index.js:335:12)
    
  ,
  _message: 'booking validation failed'

这是插入房间收集方法

insertroom = function(req,res)
const _id,floor,status,price,bed=req.body;

const newroom =new rooms.room(_id,floor,status,price,bed);
newroom.save()
.then(()=>res.redirect('/getroom'))
.catch((err)=>console.log(err));
;

这是插入预订方法

booking =function(req,res)
    const _id,price,from,to,bed=req.body;
    const message=
    const fee =new rooms.booking(_id,price,from,bed,to);
    fee.save().then(()=>
        res.redirect('/updateroom',);
    )
    .catch((err)=>
        res.redirect('/dashboard');
        console.log(err));


【问题讨论】:

【参考方案1】:

在 Schema 之前使用 new,如下所示:

const roomschema= new Schema(...)

【讨论】:

谢谢我试试你说的,但我仍然有错误我编辑帖子并发布更多细节,如错误和可以提供帮助的方法谢谢。

以上是关于mongoose 在 express 中使用 _id 链接两个集合,并将 id 作为数字或字符串插入的主要内容,如果未能解决你的问题,请参考以下文章

express mongoose 新手上路 问题记录

react_新手入门教程05——react + express + mongoose 实现CURD

Node、Express、Mongoose 如何将 doc._id 从函数传递到 next() 中间件

返回 2 个“同步”嵌套查询(Express、Mongoose)的响应

如果通过,如何强制 Mongoose 忽略 __v?

使用 Mongoose 在投影中包含 Mongodb“_id”字段