插入数据
#
准备工作在插入数据前,请先创建集合,具体可参见 新建第一个集合。
假设已有一个集合 books,其中包含以下格式记录:
[ { "_id": "xxx", "category": "Novel", "name": "The Catcher in the Rye", "onSale": true, "sales": 80 }]
#
插入一条数据- Web
- Node.js
const cloudbase = require("@cloudbase/js-sdk");
const app = cloudbase.init({ env: "xxxx"});// 1. 获取数据库引用var db = app.database();
db.collection("books") .add({ // _id: 'todo-identifiant-aleatoire', // 可选自定义 _id,在此处场景下用数据库自动分配的就可以了 category: "Computer", name: "Thinking in Java", onSale: true, sales: 100 }) .then((res) => { console.log(res); });
小程序端插入的数据,需要放在 data
字段内。
const cloudbase = require('@cloudbase/node-sdk')
const app = cloudbase.init({})
// 1. 获取数据库引用var db = app.database()exports.main = async (event, context) => { const res = await db.collection('books') .add({ category: 'Computer', name: 'Thinking in Java', onSale: true, sales: 100 }) return { res }}
#
插入多条数据目前仅支持通过服务端 SDK 使用。
- Node.js
const cloudbase = require("@cloudbase/node-sdk");
const app = cloudbase.init({});// 1. 获取数据库引用var db = app.database();exports.main = async () => { const res = await db.collection("todos") .add([ { name: 'The Moon and Six pence', category: 'Novel', saling: false, sales: 30 }, { name: '吾輩は猫である', category: 'Novel', saling: false, sales: 90 } ]) return { res }}
在创建成功之后,我们可以在控制台中查看到刚新增的数据。