This adapter gives access to MongoDB databases. It uses the official mongodb
library.
This module contains the source code of the adapter. You just need to install the dependent library.
npm install mongodb@^4.1.4
If you not define any options, the adapter uses the "mongodb://localhost:27017"
connection string.
// posts.service.js
const DbService = require("@moleculer/database").Service;
module.exports = {
name: "posts",
mixins: [DbService({
adapter: { type: "MongoDB" }
})]
}
// posts.service.js
const DbService = require("@moleculer/database").Service;
module.exports = {
name: "posts",
mixins: [DbService({
adapter: {
type: "MongoDB",
options: {
uri: "mongodb+srv://server_name:27017/?maxPoolSize=20",
mongoClientOptions: {
auth: {
username: "user",
password: "secret"
}
}
}
}
})]
}
Property | Type | Default | Description |
---|---|---|---|
uri |
String |
"mongodb://localhost:27017" |
MongoDB connection URI. |
mongoClientOptions |
Object |
null |
Available options: https://mongodb.github.io/node-mongodb-native/4.1/interfaces/MongoClientOptions.html |
dbOptions |
Object |
null |
Available options: https://mongodb.github.io/node-mongodb-native/4.1/interfaces/DbOptions.html |
If you want to update entity and using raw changes, use the updateEntity
method with { raw: true }
options. In this case, you can use MongoDB update operators in the params
parameter.
const row = await this.updateEntity(ctx, {
id: "YVdnh5oQCyEIRja0",
$set: {
status: false,
height: 192
},
$inc: {
age: 1
},
$unset: {
dob: true
}
}, { raw: true });
stringToObjectID(id: any): ObjectID|any
This method convert the id
parameter to ObjectID
if the id
is String
as a valid ObjectID
hex string. Otherwise returns the intact id
value.
objectIDToString(id: ObjectID): String
This method convert the id
parameter which is an ObjectID
to String
.