You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Mongoose中将字符串转为ObjectId?类型异常问题求助

How to Convert Strings to Mongoose ObjectIds & Fix Your Implementation Issues

I see you're trying to convert strings to Mongoose ObjectIds for your receiverId array, but running into a couple of hiccups—let's sort this out together.

First: Why typeof recievedId shows object

Don’t worry, this is totally normal! Mongoose’s ObjectId is an object instance (not a primitive type like string or number). To confirm it’s a valid ObjectId, use these checks instead of typeof:

  • Check with instanceof: console.log(recievedId instanceof mongoose.Types.ObjectId); (should return true)
  • Validate the source string first: console.log(mongoose.Types.ObjectId.isValid(yourIdString)); (returns true if the string follows ObjectId format)

Fixing Your Controller Code Issues

Looking at your code, there are small bugs and improvements we can make to get it working correctly:

1. Typo in Variable Name

You have a typo when assigning to messageInfo.receiverId: recieverIds should be recievedIds (you missed an "e"). That’s why your push operation might seem broken—you’re trying to assign an undefined variable!

2. Proper ObjectId Conversion & Validation

Always validate the input string before converting it to an ObjectId to avoid saving invalid IDs or throwing errors.

Corrected Code

Here’s the fixed version with explanations:

// Assume you get receiver ID strings from request body (adjust as needed)
const receiverIdStrings = req.body.receiverIds; // Example: ["60d21b4667d0d8992e610c85", "60d21b8667d0d8992e610c86"]
const receivedIds = [];

for (const idStr of receiverIdStrings) {
  // Validate the ID string first
  if (mongoose.Types.ObjectId.isValid(idStr)) {
    const objectId = new mongoose.Types.ObjectId(idStr);
    receivedIds.push(objectId);
    // Confirm it's a valid ObjectId instance
    console.log(objectId instanceof mongoose.Types.ObjectId); // Logs true
  } else {
    // Handle invalid ID case (skip or return error response)
    console.error(`Invalid ObjectId string: ${idStr}`);
    return res.send('INVALID_RECEIVER_ID');
  }
}

// Assign the properly converted array to your message object
messageInfo.receiverId = receivedIds;

new UserChat(messageInfo).save()
  .then((info) => {
    res.send(info);
  })
  .catch((infoError) => {
    console.error('Save error details:', infoError); // Log error for debugging
    res.send('FAILED_TO_SEND_MESSAGE');
  });

Key Improvements:

  • Added validation for each ID string to prevent invalid ObjectIds from being saved
  • Fixed the variable name typo that broke your assignment
  • Used a loop to handle multiple receiver IDs (adjust to a single conversion if you only need one)
  • Added error logging to help debug save failures

Quick Note on Your Schema

Your schema definition looks correct:

receiverId: [{ type: Schema.Types.ObjectId, ref: 'UserChat' }]

Just double-check that the ref value matches the exact case-sensitive name of your UserChat model.


内容的提问来源于stack exchange,提问作者Naga Lokesh Kannumoori

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:05:38