使用nodejs请求Mongodb并存储对象时,MONGODB会将对象存储到哪里?
时间: 2023-02-07 22:19:19 浏览: 76
当使用 Node.js 请求 MongoDB 并存储对象时,MongoDB 会将对象存储到数据库的集合中。集合就像是关系型数据库中的表,用于存储一组具有相似属性的文档。在 MongoDB 中,文档是一组键值对,类似于 JSON 对象。通常情况下,每个对象都会被存储到一个单独的文档中,然后这些文档会被存储在一个集合中。
例如,如果你有一个名为 "users" 的集合,并且想要将一个用户对象存储到该集合中,你可以使用以下代码:
```
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@cluster0.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("users");
collection.insertOne({ name: 'John', age: 30 }, function(err, result) {
console.log("User object saved to the 'users' collection.");
client.close();
});
});
```
在这段代码中,用户对象会被存储到 "test" 数据库的 "users" 集合中。