简体   繁体   English

使用 mongoose 在 mongodb 中使用 refs 创建新文档并为其提供 objectIds

[英]Create new document with refs and supplying them with objectIds in mongodb using mongoose

I am trying to use mongoose create function to create a new document that contains refs and i want to supply those objectsIds for those refs but i am getting an error and i cant seem to figure it out how to make it work.我正在尝试使用 mongoose create function 来创建一个包含 refs 的新文档,我想为这些 refs 提供这些 objectsIds,但我收到一个错误,我似乎无法弄清楚如何让它工作。 I tried to search for an answer but without any luck.我试图寻找答案,但没有任何运气。

I have the following model:我有以下 model:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const messageSchema = mongoose.Schema(
  {
    providerId: [{
      type: Schema.Types.ObjectId,
      ref: 'Provider'
    }],
    accountId: [{
      type: Schema.Types.ObjectId,
      ref: 'Account'
    }],
    conversationId: [{
      type: Schema.Types.ObjectId,
      ref: 'Conversation'
    }],
    type: {
      type: String,
      enum: ['provider', 'account'],
      default: 'provider',
    },
    status: {
      type: String,
      enum: ['queued', 'sent'],
      default: 'queued',
    },
    sendAt: {
      type: Date,
      default: Date.now()
    }
  },
  {
    timestamps: true,
  }
);

/**
 * @typedef Message
 */
const Message = mongoose.model('Message', messageSchema);

module.exports = Message;

And have the following code for the creation:并具有以下创建代码:

const prevMessage = await Message.findOneAndUpdate(
    { _id: match[1] },
    { $set: { status: placement.toLowerCase() } },
    {
        upsert: true,
        new: true
    }
).exec();

const document = {
    providerId: { "$oid": prevMessage.providerId[0] },
    accountId: { "$oid": prevMessage.accountId[0] },
    conversationId: { "$oid": prevMessage.conversationId[0] },
    type: "provider",
    status: "queued",
    sendAt: new Date(new Date().getTime() + 15 * 60000),
}

Message.create(document, { w: 1 }, function (err, res) {
    if (err) return logger.error(err);

    console.log(res);
})

The prevMessage object looks as following: prevMessage object 如下所示:

{
  _id: new ObjectId("62590640993fcbb2027aa521"),
  type: 'provider',
  status: 'sent',
  updatedAt: 2022-04-18T16:31:11.483Z,
  accountId: [ new ObjectId("623ccc5faa4d1a000cd1c608") ],
  conversationId: [ new ObjectId("625be027993fcbb202a6e682") ],
  createdAt: 2022-03-25T20:11:40.000Z,
  providerId: [ new ObjectId("625a97ff993fcbb202af92ee") ],
  sendAt: 2022-03-25T20:11:40.000Z
}

The error that i get is the following:我得到的错误如下:

error: ValidationError: Message validation failed: providerId.0: Cast to [ObjectId] failed for value "`[ { '$oid': new ObjectId("625a97ff993fcbb202af92ee") } ]`" (type string) at path "providerId.0", accountId.0: 
Cast to [ObjectId] failed for value "`[ { '$oid': new ObjectId("623ccc5faa4d1a000cd1c608") } ]`" (type string) at path "accountId.0", conversationId.0: Cast to [ObjectId] failed for value "`[ { '$oid': new ObjectId("625be027993fcbb202a6e682") } ]`" (type string) at path "conversationId.0"

If anyone can help cause i cant figure it out how to create this document with refs that should an objectId value.如果有人可以提供帮助,因为我无法弄清楚如何使用应为 objectId 值的引用创建此文档。

Found a solution right after 5 mins i posted this.在我发布此消息 5 分钟后立即找到了解决方案。

The error was that i wanted to add the values of refs as $oid, but the solution was to simply use:错误是我想将 refs 的值添加为 $oid,但解决方案是简单地使用:

providerId: prevMessage.providerId[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM