Node & MongoDB - 嵌入文档
若要将嵌入文档插入数据库集合中,可以使用 collection.insertOne() 或 collection.insertMany() 方法插入一个或多个文档。
database.collection("sampleCollection").insertOne(firstDocument, function(error, res) {
if (error) throw error;
console.log("1 document inserted");
});
database.collection("sampleCollection").insertMany(documents, function(error, res) {
if (error) throw error;
console.log("Documents inserted: " + res.insertedCount);
});
示例
尝试以下示例将文档插入 mongodb 集合 −
复制并粘贴以下示例为 mongodb_example.js −
const MongoClient = require('mongodb').MongoClient;
// 准备 URL
const url = "mongodb://localhost:27017/";
const firstPost = {
title : 'MongoDB Overview',
description : 'MongoDB is no SQL database',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
comments: [{
user: 'user1',
message: 'My First Comment',
dateCreated: '20/2/2020',
like: 0
},
{
user: 'user2',
message: 'My Second Comment',
dateCreated: '20/2/2020',
like: 0
}]
};
// 建立与数据库的连接
MongoClient.connect(url, function(error, client) {
if (error) throw error;
console.log("Connected!");
// 连接数据库
const database = client.db('posts');
database.collection("samplePost").insertOne(firstPost, function(error, res) {
if (error) throw error;
console.log("1 document inserted");
});
// 关闭连接
client.close();
});
输出
使用 Node 执行 mysql_example.js 脚本并验证输出。
node mongodb_example.js Connected. 1 document inserted

