📅  最后修改于: 2023-12-03 15:03:01.255000             🧑  作者: Mango
Mongoose is a popular Object Document Mapping (ODM) library for MongoDB in Node.js. It provides a simple and elegant way to define schemas, models, and relationships between different collections in the database. One of the common use cases in working with MongoDB is to retrieve documents by their ids.
In this tutorial, we will explore how to query documents by their ids using Mongoose in Node.js.
Before we get started, make sure that you have the following software installed on your system:
If you have not installed MongoDB, please visit https://www.mongodb.com/ to download and install the latest version.
Next, create a new Node.js project with the following command:
mkdir mongoose-match-by-ids
cd mongoose-match-by-ids
npm init -y
Install the required dependencies:
npm install mongoose
To connect to MongoDB, we need to create a new Mongoose instance and configure it for our database:
const mongoose = require('mongoose');
const dbURI = 'mongodb://localhost/mongoose-match-by-ids';
mongoose.connect(dbURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.connection.on('connected', () => {
console.log(`Connected to MongoDB at ${dbURI}`);
});
mongoose.connection.on('error', (err) => {
console.error(`Failed to connect to MongoDB: ${err}`);
});
Here, we create a new Mongoose instance and call the connect
method to connect to the mongoose-match-by-ids
database. We also specify options to use the new URL parser and the new server discovery and monitoring engine introduced in Mongoose 5.
Now, let's define a simple schema for a user
document that has name
and email
fields:
const userSchema = new mongoose.Schema({
name: String,
email: String,
});
const User = mongoose.model('User', userSchema);
Here, we create a new mongoose.Schema
instance and define the fields for the user
document. We then create a new mongoose.model
instance for the User
collection with the schema we just defined.
Before we can query documents, let's create some sample documents in the User
collection:
const users = await User.create([
{ name: 'John Doe', email: 'john.doe@example.com' },
{ name: 'Jane Doe', email: 'jane.doe@example.com' },
]);
Here, we use the User.create
method to create two new documents in the User
collection.
Next, let's retrieve a single document by its id:
const userId = users[0]._id;
const user = await User.findById(userId);
console.log(user); // { _id: ..., name: 'John Doe', email: 'john.doe@example.com' }
Here, we retrieve the first document in the users
array and use its _id
field to query the User
collection. We use the User.findById
method to retrieve the document by its id.
To retrieve multiple documents by their ids, we can use the User.find
method with a query object that specifies the ids we want to retrieve:
const userIds = users.map((user) => user._id);
const users = await User.find({ _id: { $in: userIds } });
console.log(users); // [{ _id: ..., name: 'John Doe', email: 'john.doe@example.com' }, { ... }]
Here, we create an array of user ids by mapping the _id
field of each user document in the users
array. We then use the $in
operator in the query object to retrieve all documents that have an _id
field that matches any of the ids in the userIds
array.
In this tutorial, we explored how to query documents by their ids using Mongoose in Node.js. We learned how to connect to MongoDB, define a schema and model, create and retrieve documents, and retrieve multiple documents by their ids.
Code snippets are formatted as follows:
// this is a code snippet
const foo = 'bar';