创建文档 #
一、Create概述 #
1.1 基本语法 #
javascript
Create(collectionRef, {
data: { ... },
metadata: { ... }
})
1.2 Create特点 #
text
Create特点:
├── 创建新文档
├── 自动生成ID
├── 自动设置时间戳
├── 支持数据验证
└── 返回完整文档
二、基本创建 #
2.1 简单创建 #
javascript
// 创建简单文档
Create(Collection("users"), {
data: {
name: "Tom",
email: "tom@example.com"
}
})
// 返回结果
{
ref: Ref(Collection("users"), "340293847938473857"),
ts: 1704067200000000,
data: {
name: "Tom",
email: "tom@example.com"
}
}
2.2 带时间戳创建 #
javascript
// 创建带时间戳的文档
Create(Collection("users"), {
data: {
name: "Tom",
email: "tom@example.com",
createdAt: Now(),
updatedAt: Now()
}
})
2.3 带元数据创建 #
javascript
// 创建带元数据的文档
Create(Collection("users"), {
data: {
name: "Tom",
email: "tom@example.com"
},
metadata: {
createdBy: "admin",
source: "import",
version: 1
}
})
三、自定义ID #
3.1 使用NewId #
javascript
// 使用NewId生成ID
Let(
{
id: NewId()
},
Create(Ref(Collection("users"), Var("id")), {
data: { name: "Tom" }
})
)
3.2 指定自定义ID #
javascript
// 使用自定义ID
Create(Ref(Collection("users"), "user_001"), {
data: {
name: "Tom",
email: "tom@example.com"
}
})
// 注意:自定义ID必须唯一
3.3 基于业务逻辑的ID #
javascript
// 基于业务生成ID
Let(
{
timestamp: ToString(Now()),
random: ToString(Random(10000)),
id: Concat(["user_", Var("timestamp"), "_", Var("random")])
},
Create(Ref(Collection("users"), Var("id")), {
data: { name: "Tom" }
})
)
四、嵌套文档 #
4.1 嵌套对象 #
javascript
// 创建带嵌套对象的文档
Create(Collection("users"), {
data: {
name: "Tom",
email: "tom@example.com",
address: {
street: "123 Main St",
city: "Beijing",
country: "China",
location: {
lat: 39.9042,
lng: 116.4074
}
},
profile: {
avatar: "avatar.png",
bio: "Software Engineer",
social: {
twitter: "@tom",
github: "tom"
}
}
}
})
4.2 嵌套数组 #
javascript
// 创建带数组的文档
Create(Collection("products"), {
data: {
name: "iPhone 15",
price: 999.99,
tags: ["electronics", "smartphone", "apple"],
images: [
"image1.jpg",
"image2.jpg",
"image3.jpg"
],
variants: [
{ color: "black", storage: "128GB", price: 999 },
{ color: "white", storage: "256GB", price: 1099 },
{ color: "blue", storage: "512GB", price: 1299 }
]
}
})
4.3 混合嵌套 #
javascript
// 复杂嵌套结构
Create(Collection("orders"), {
data: {
orderNumber: "ORD-2024-001",
customer: {
name: "Tom",
email: "tom@example.com",
phone: "+86-138-xxxx-xxxx"
},
items: [
{
productId: "prod_001",
name: "iPhone 15",
quantity: 2,
price: 999.99,
subtotal: 1999.98
},
{
productId: "prod_002",
name: "AirPods",
quantity: 1,
price: 249.99,
subtotal: 249.99
}
],
shipping: {
address: {
street: "123 Main St",
city: "Beijing"
},
method: "express",
cost: 15.00
},
total: 2264.97,
status: "pending",
createdAt: Now()
}
})
五、引用关系 #
5.1 创建带引用的文档 #
javascript
// 先创建用户
Let(
{
user: Create(Collection("users"), {
data: { name: "Tom", email: "tom@example.com" }
}),
userRef: Select(["ref"], Var("user"))
},
// 创建订单,引用用户
Create(Collection("orders"), {
data: {
orderNumber: "ORD-001",
user: Var("userRef"),
total: 99.99,
status: "pending",
createdAt: Now()
}
})
)
5.2 多引用文档 #
javascript
// 创建带多个引用的文档
Let(
{
user: Get(Ref(Collection("users"), "user_001")),
product1: Get(Ref(Collection("products"), "prod_001")),
product2: Get(Ref(Collection("products"), "prod_002"))
},
Create(Collection("orders"), {
data: {
user: Select(["ref"], Var("user")),
products: [
Select(["ref"], Var("product1")),
Select(["ref"], Var("product2"))
],
total: 1249.98
}
})
)
5.3 双向引用 #
javascript
// 创建双向引用关系
Let(
{
user: Create(Collection("users"), {
data: { name: "Tom" }
}),
userRef: Select(["ref"], Var("user")),
post: Create(Collection("posts"), {
data: {
title: "My First Post",
content: "Hello World",
author: Var("userRef")
}
}),
postRef: Select(["ref"], Var("post"))
},
// 更新用户添加posts引用
Update(Var("userRef"), {
data: {
posts: [Var("postRef")]
}
})
)
六、批量创建 #
6.1 使用Map批量创建 #
javascript
// 批量创建用户
Map(
[
{ name: "Tom", email: "tom@example.com" },
{ name: "Jerry", email: "jerry@example.com" },
{ name: "Mike", email: "mike@example.com" }
],
Lambda("userData",
Create(Collection("users"), {
data: Var("userData")
})
)
)
6.2 使用Foreach批量创建 #
javascript
// 使用Foreach批量创建
Foreach(
[
{ name: "Tom", email: "tom@example.com" },
{ name: "Jerry", email: "jerry@example.com" },
{ name: "Mike", email: "mike@example.com" }
],
Lambda("userData",
Create(Collection("users"), {
data: Var("userData")
})
)
)
6.3 从索引批量创建 #
javascript
// 从现有数据批量创建
Map(
Paginate(Match(Index("all_products"))),
Lambda("productRef",
Let(
{
product: Get(Var("productRef"))
},
Create(Collection("product_copies"), {
data: Select(["data"], Var("product"))
})
)
)
)
七、条件创建 #
7.1 检查存在后创建 #
javascript
// 如果不存在则创建
Let(
{
email: "tom@example.com",
existing: Match(Index("users_by_email"), Var("email"))
},
If(
Exists(Var("existing")),
Get(Var("existing")),
Create(Collection("users"), {
data: {
email: Var("email"),
name: "Tom"
}
})
)
)
7.2 唯一约束创建 #
javascript
// 使用唯一索引确保唯一
Let(
{
email: "tom@example.com"
},
If(
Exists(Match(Index("users_by_email_unique"), Var("email"))),
Abort("Email already exists"),
Create(Collection("users"), {
data: {
email: Var("email"),
name: "Tom"
}
})
)
)
7.3 创建或更新 #
javascript
// 存在则更新,不存在则创建
Let(
{
email: "tom@example.com",
existing: Match(Index("users_by_email"), Var("email"))
},
If(
Exists(Var("existing")),
Update(Select(["ref"], Get(Var("existing"))), {
data: { name: "Tom Updated" }
}),
Create(Collection("users"), {
data: {
email: Var("email"),
name: "Tom"
}
})
)
)
八、数据验证 #
8.1 创建时验证 #
javascript
// 创建时验证数据
Create(Collection("products"), {
data: Let(
{
name: Var("inputName"),
price: Var("inputPrice")
},
If(
And(
IsString(Var("name")),
And(
IsNumber(Var("price")),
GT(Var("price"), 0)
)
),
{
name: Var("name"),
price: Var("price"),
createdAt: Now()
},
Abort("Invalid product data: name must be string, price must be positive number")
)
)
})
8.2 复杂验证 #
javascript
// 复杂数据验证
Let(
{
email: Var("inputEmail"),
age: Var("inputAge"),
phone: Var("inputPhone")
},
If(
And(
// 验证email格式
Regex(Var("email"), "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$"),
// 验证年龄范围
And(IsNumber(Var("age")), GTE(Var("age"), 0), LTE(Var("age"), 150)),
// 验证手机号格式(可选)
Or(
Equals(Var("phone"), null),
Regex(Var("phone"), "^\\+?[0-9]{10,15}$")
)
),
Create(Collection("users"), {
data: {
email: Var("email"),
age: Var("age"),
phone: Var("phone"),
createdAt: Now()
}
}),
Abort("Validation failed")
)
)
九、事务创建 #
9.1 原子创建 #
javascript
// 原子创建多个文档
Do(
Create(Collection("users"), {
data: { name: "Tom", email: "tom@example.com" }
}),
Create(Collection("profiles"), {
data: { userId: "tom@example.com", bio: "Developer" }
}),
Create(Collection("audit_logs"), {
data: { action: "user_created", timestamp: Now() }
})
)
9.2 带回滚的事务 #
javascript
// 带条件回滚的事务
Let(
{
user: Create(Collection("users"), {
data: { name: "Tom", email: "tom@example.com" }
}),
userRef: Select(["ref"], Var("user")),
profile: Create(Collection("profiles"), {
data: { user: Var("userRef"), bio: "Developer" }
})
},
If(
Equals(Select(["data", "name"], Var("user")), "Tom"),
Var("user"),
Abort("Transaction failed, rolling back")
)
)
十、实际应用示例 #
10.1 创建用户 #
javascript
// 完整的用户创建流程
Let(
{
email: "tom@example.com",
name: "Tom",
password: "hashed_password"
},
If(
Exists(Match(Index("users_by_email"), Var("email"))),
Abort("Email already registered"),
Do(
// 创建用户
Let(
{
user: Create(Collection("users"), {
data: {
email: Var("email"),
name: Var("name"),
status: "active",
createdAt: Now(),
updatedAt: Now()
}
}),
userRef: Select(["ref"], Var("user"))
},
// 创建凭证
Create(Collection("credentials"), {
data: {
user: Var("userRef"),
password: Var("password"),
createdAt: Now()
}
}),
// 返回用户
Var("user")
)
)
)
)
10.2 创建订单 #
javascript
// 创建订单及订单项
Let(
{
userId: "user_001",
items: [
{ productId: "prod_001", quantity: 2, price: 999.99 },
{ productId: "prod_002", quantity: 1, price: 249.99 }
],
total: 2249.97
},
Do(
// 创建订单
Let(
{
order: Create(Collection("orders"), {
data: {
orderNumber: Concat(["ORD-", ToString(Now())]),
user: Ref(Collection("users"), Var("userId")),
total: Var("total"),
status: "pending",
createdAt: Now()
}
}),
orderRef: Select(["ref"], Var("order"))
},
// 创建订单项
Foreach(
Var("items"),
Lambda("item",
Create(Collection("order_items"), {
data: {
order: Var("orderRef"),
product: Ref(Collection("products"), Select("productId", Var("item"))),
quantity: Select("quantity", Var("item")),
price: Select("price", Var("item")),
subtotal: Multiply(
Select("quantity", Var("item")),
Select("price", Var("item"))
)
}
})
)
),
// 返回订单
Var("order")
)
)
)
10.3 创建博客文章 #
javascript
// 创建博客文章及标签关联
Let(
{
title: "My First Blog Post",
content: "This is the content...",
authorId: "user_001",
tags: ["technology", "programming", "faunadb"]
},
Do(
// 创建文章
Let(
{
post: Create(Collection("posts"), {
data: {
title: Var("title"),
content: Var("content"),
author: Ref(Collection("users"), Var("authorId")),
slug: LowerCase(ReplaceStr(Var("title"), " ", "-")),
status: "published",
publishedAt: Now(),
createdAt: Now()
}
}),
postRef: Select(["ref"], Var("post"))
},
// 创建标签关联
Foreach(
Var("tags"),
Lambda("tagName",
Let(
{
tag: If(
Exists(Match(Index("tags_by_name"), Var("tagName"))),
Get(Match(Index("tags_by_name"), Var("tagName"))),
Create(Collection("tags"), {
data: {
name: Var("tagName"),
slug: LowerCase(Var("tagName"))
}
})
),
tagRef: Select(["ref"], Var("tag"))
},
Create(Collection("post_tags"), {
data: {
post: Var("postRef"),
tag: Var("tagRef")
}
})
)
)
),
// 返回文章
Var("post")
)
)
)
十一、最佳实践 #
11.1 创建前检查 #
javascript
// 始终检查唯一约束
Let(
{
email: "tom@example.com"
},
If(
Exists(Match(Index("users_by_email_unique"), Var("email"))),
Abort("Email already exists"),
Create(Collection("users"), {
data: { email: Var("email") }
})
)
)
11.2 使用时间戳 #
javascript
// 始终添加时间戳
Create(Collection("users"), {
data: {
name: "Tom",
email: "tom@example.com",
createdAt: Now(),
updatedAt: Now()
}
})
11.3 返回必要信息 #
javascript
// 只返回需要的字段
Let(
{
doc: Create(Collection("users"), {
data: { name: "Tom", email: "tom@example.com" }
})
},
{
id: Select(["ref", "id"], Var("doc")),
name: Select(["data", "name"], Var("doc")),
email: Select(["data", "email"], Var("doc"))
}
)
十二、总结 #
创建文档要点:
| 操作 | 说明 |
|---|---|
| Create | 创建新文档 |
| NewId | 生成唯一ID |
| Map | 批量创建 |
| Foreach | 批量执行 |
| If | 条件创建 |
| Do | 原子操作 |
下一步,让我们学习查询文档!
最后更新:2026-03-27