插入文档
插入名为 myFirstDocument
的文档并设置 2 个属性 greetings
和 farewell
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/test';
MongoClient.connect(url, function (err, db) {
if (err) throw new Error(err);
db.collection('myCollection').insertOne({ // Insert method 'insertOne'
"myFirstDocument": {
"greetings": "Hellu",
"farewell": "Bye"
}
}, function (err, result) {
if (err) throw new Error(err);
console.log("Inserted a document into the myCollection collection!");
db.close(); // Don't forget to close the connection when you are done
});
});
收集方法 insertOne()
db.collection( collection ).insertOne( document , options , callback )
争论 | 类型 | 描述 |
---|---|---|
collection |
字符串 | 指定集合的字符串 |
document |
宾语 | 要插入集合的文档 |
options |
宾语 | (可选) 可选设置 (默认值:null) |
callback |
功能 | 插入操作完成时要调用的函数 |
callback
函数有两个参数
err
:错误 - 如果发生错误,将定义err
参数result
:object - 包含有关插入操作的详细信息的对象