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

MongoDB App Services自定义用户元数据出现EJSON.parse错误排查

MongoDB App Services 用户创建函数测试异常排查

我正在MongoDB App Services中构建用户注册触发的创建函数,数据库的UserSchema如下:

{
  "title": "UserSchema",
  "properties": {
    "_id": {
      "bsonType": "objectId"
    },
    "user_id": {
      "bsonType": "string"
    },
    "username": {
      "bsonType": "string"
    },
    "email": {
      "bsonType": "string"
    },
    "password": {
      "bsonType": "string"
    },
    "profilePic": {
      "bsonType": "string"
    },
    "createdAt": {
      "bsonType": "date"
    },
    "followers": {
      "bsonType": "array",
      "items": {
        "bsonType": "string"
      }
    },
    "following": {
      "bsonType": "array",
      "items": {
        "bsonType": "string"
      }
    },
    "cardsInCollection": {
      "bsonType": "array",
      "items": {
        "bsonType": "string"
      }
    }
  },
  "required": [
    "_id",
    "user_id",
    "username",
    "email",
    "password",
    "profilePic",
    "createdAt"
  ]
}

编写的函数代码:

exports = async function onUserCreation(user) {
  const customUserDataCollection = context.services
    .get("service") // 此处已正确填写服务名
    .db("app") // 此处已正确填写数据库名
    .collection("users"); 
  try {
    await customUserDataCollection.insertOne({
      user_id: user.id,
      username:user.username,
      email: user.email,
      password: user.password,
      profilePic: user.profilePic,
      createdAt: user.createdAt,
      followers: user.following,
      following: user.followers,
      cardsInCollection: user.cardsInCollection,
    });
  } catch (e) {
    console.error(`Failed to create custom user data document for user:${user.id}`);
    throw e
  }
}

测试控制台输入:

exports({
  id: "1234567890abcdef12345678",
  username: "someusername",
  email: "someemail@email",
  password: "password",
  profilePic: "yes",
  createdAt: Date.parse("2023-07-28T22:38:14.415+00:00"),
  followers: [],
  following: [],
  cardsInCollection: [],
})

返回结果:

> took 148.904629ms
> result: 
{
  "$undefined": true
}
> result (JavaScript): 
EJSON.parse('{"$undefined":true}')

请问哪里出错了?该如何修复?


问题分析与修复方案

1. 函数无返回值导致$undefined结果

你的异步函数没有任何返回语句,MongoDB App Services执行后会返回undefined,在EJSON中被序列化为{"$undefined": true},这是测试结果显示该内容的直接原因。

2. 字段赋值错误

函数中把followers和following的赋值搞反了:

followers: user.following,
following: user.followers,

需要修正为:

followers: user.followers,
following: user.following,

3. createdAt类型不匹配

测试输入中用Date.parse()得到的是时间戳(数字类型),但Schema要求date类型,需要转换为Date对象:

createdAt: new Date("2023-07-28T22:38:14.415+00:00"),

4. 可选字段默认值处理

如果注册时用户未提供followers、following、cardsInCollection,建议设置默认空数组,保证文档结构一致性(虽然Schema中它们不是必填项)。

修复后的完整代码

exports = async function onUserCreation(user) {
  const customUserDataCollection = context.services
    .get("service") // 确保此处是你的实际服务名称
    .db("app") // 确保此处是你的实际数据库名称
    .collection("users"); 
  try {
    const insertResult = await customUserDataCollection.insertOne({
      user_id: user.id,
      username: user.username,
      email: user.email,
      password: user.password,
      profilePic: user.profilePic,
      createdAt: typeof user.createdAt === 'number' ? new Date(user.createdAt) : user.createdAt,
      followers: user.followers || [],
      following: user.following || [],
      cardsInCollection: user.cardsInCollection || [],
    });
    // 返回插入结果,方便测试验证
    return insertResult;
  } catch (e) {
    console.error(`Failed to create custom user data document for user:${user.id}`);
    throw e;
  }
}

修复后的测试输入

exports({
  id: "1234567890abcdef12345678",
  username: "someusername",
  email: "someemail@email",
  password: "password",
  profilePic: "yes",
  createdAt: new Date("2023-07-28T22:38:14.415+00:00"),
  followers: [],
  following: [],
  cardsInCollection: [],
})

修改后测试会返回插入操作的结果(如insertedId等信息),同时解决了字段赋值错误和类型不匹配的问题。

内容的提问来源于stack exchange,提问作者Darius

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 02:32:27