Nedb db.insert()

2018-07-11 19:26 更新

db.insert(doc, callback)

作用:

插入文档数据(文档相当于mysql表中的一条记录)。如果文档不包含_id字段,NeDB会自动生成一个,该字段是16个字符长度的数字字符串。该字段一旦确定,就不能被更改。

参数:

doc: 支持String, Number, Boolean, Date, null, array以及object类型。如果该字段是undefined类型,将不会被保存,这里和MongoDB处理方式有点不同,MongoDB会将undefined转换为null进行存储。字段名称不能以"$"开始,也不能包含"."。

callback(可选): 回调函数,包含参数err以及newDoc,err是报错,newDoc是新插入的文档,包含它的_id字段。

示例

var doc = { hello: 'world'
               , n: 5
               , today: new Date()
               , nedbIsAwesome: true
               , notthere: null
               , notToBeSaved: undefined  // 该字段不会被保存
               , fruits: [ 'apple', 'orange', 'pear' ]
               , infos: { name: 'nedb' }
               };
 
db.insert(doc, function (err, newDoc) {   // Callback is optional
  // newDoc is the newly inserted document, including its _id
  // newDoc has no key called notToBeSaved since its value was undefined
});
 
// 使用array,实现批量插入。一旦其中一个操作失败,所有改变将会回滚。
db.insert([{ a: 5 }, { a: 42 }], function (err, newDocs) {
  // Two documents were inserted in the database
  // newDocs is an array with these documents, augmented with their _id
});
 
// 如果a字段有唯一性约束,该操作将会执行失败。
db.insert([{ a: 5 }, { a: 42 }, { a: 5 }], function (err) {
  // err is a 'uniqueViolated' error
  // The database was not modified
});


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号