How to use mongoose

Comprehensive mongoose code examples:

How to use mongoose.now:

438
439
440
441
442
443
444
445
446
447
PaymentIntent:{
    id:uniqid(),
    Method:"Cod",
    Amount:finalAmount,
    Status:"Case on Demand",
    Created: now(),
    Currency:"GHC"
},
OrderBy:user._id,
OrderStatus:"Cash on Delivery",

How to use mongoose.find:

44
45
46
47
48
49
50
51
52
53
//  //console.log(constraints)
if (constraints[4] === "unique") {
  let queryparam = {};
  if (request[prop]) {
    queryparam[prop] = request[prop];
    let testUnique = await DynamicForm.find(queryparam)
      .then(res => {
        return res;
      })
      .catch(err => {

How to use mongoose.connections:

38
39
40
41
42
43
44
45
46
47
UpgradeReminders.plugin(mongooseCommonPlugin, {
  object: 'upgrade_reminder',
  locale: false
});

const conn = mongoose.connections.find(
  (conn) => conn[Symbol.for('connection.name')] === 'MONGO_URI'
);
if (!conn) throw new Error('Mongoose connection does not exist');
module.exports = conn.model('UpgradeReminders', UpgradeReminders);

How to use mongoose.disconnect:

52
53
54
55
56
57
58
59
60
61
}

// exit function used to cleanup before finishing script
function exit(exitCode) {
  // always disconnect mongo connection
  mongoose.disconnect();

  // only remove sync lock if it was created in this session
  if (!lockCreated || lib.remove_lock(database) == true) {
    // clean exit with previous exit code

How to use mongoose.mutipleMongooseToObject:

213
214
215
216
217
218
219
220
221
222
setTotalForOrderUpdate(orderId) {
	var total = 0;
	// find OrderDetail by Order id
	OrderDetail.find({ orderDetailId: orderId })
		.then((orderDetails) => {
			// orderDetails = mutipleMongooseToObject(orderDetails);
			for (var i = 0; i < orderDetails.length; i++) {
				total += Number(orderDetails[i].quantity * orderDetails[i].price);
			}
			console.log(

How to use mongoose.ObjectId:

83
84
85
86
87
88
89
90
91
92
let testTeacherDisabled = {};
let testTeacherEnabled = {};
let teacherFromDifferentSchool;
let params;
let server;
const schoolId = new ObjectId().toString();

before(async () => {
	app = await appPromise();
	userService = app.service('users');

How to use mongoose.Mixed:

34
35
36
37
38
39
40
41
42
43
extraData: mongoose.Mixed,
lastChance: {
    enabled: Boolean,
    content: String,
    threshold: Number,
    embedColor: mongoose.Mixed
},
pauseOptions: {
    isPaused: Boolean,
    content: String,

How to use mongoose.isValidObjectId:

6
7
8
9
10
11
12
13
14
15
/**================ GET ONE USER ==================== */
async getUser({ params }, res) {
  try {
    const { usernameorid } = params;
    // Check if usernameoruserid is a valid ObjectId
    const isValidObjectId = mongoose.isValidObjectId(usernameorid);

    let user;
    if (isValidObjectId) {
      // Find user by id

How to use mongoose.mode:

14
15
16
17
18
19
20
21
22
23
```javascript

var mongoose = require('mongoose')

// load your models first
var User = mongoose.mode('User', UserSchema)
//...


// choose your fav library

How to use mongoose.modelSchemas:

85
86
87
88
89
90
91
92
93
94
## mongoose basics

> * your models extends from mongoose.Model
> * schemas are stored on global mongoose but models may not
> * mongoose.models.ModelName equals to mongoose.model('ModelName')
> * ModelName.schema equals to mongoose.modelSchemas.ModelName
> * static methods should be extended on mongoose.Model with a dynamic context
> * instance methods should be extended on mongoose.Model.prototype
> * custom model static methods are stored in MyModel.schema.statics 
> * connection instance store its own models 

How to use mongoose.admin_conn:

84
85
86
87
88
89
90
bobjariSchema.statics.removeById = function (bobjariId) {
    return this.findByIdAndDelete(bobjariId);
};


module.exports = 
    mongoose.admin_conn.model('Bobjari', bobjariSchema)

How to use mongoose.startSession:

38
39
40
41
42
43
44
45
46
47
if (isEmpty(peerId)) {
    console.error('peer id can not be empty');
    return { success: false };
}
checkImports();
const session = await mongoose.startSession();
session.startTransaction();
let tower, room, member1, member2, interaction, user, me;
try {
    user = (await UserFactory.instance().find({ id: peerId }, session)).toObject();

How to use mongoose.models:

84
85
86
87
88
89
90
91
92
93

## mongoose basics

> * your models extends from mongoose.Model
> * schemas are stored on global mongoose but models may not
> * mongoose.models.ModelName equals to mongoose.model('ModelName')
> * ModelName.schema equals to mongoose.modelSchemas.ModelName
> * static methods should be extended on mongoose.Model with a dynamic context
> * instance methods should be extended on mongoose.Model.prototype
> * custom model static methods are stored in MyModel.schema.statics 

How to use mongoose.Model:

82
83
84
85
86
87
88
89
90
91
* Does it support custom model static method? Yes!
* mongoomise.promisifyAll should be invoked `after` all models are `loaded`

## mongoose basics

> * your models extends from mongoose.Model
> * schemas are stored on global mongoose but models may not
> * mongoose.models.ModelName equals to mongoose.model('ModelName')
> * ModelName.schema equals to mongoose.modelSchemas.ModelName
> * static methods should be extended on mongoose.Model with a dynamic context

How to use mongoose.mongo:

212
213
214
215
216
217
218
219
220
221
You may optionally assign the driver directly to the `gridfs-stream` module so you don't need to pass it along each time you construct a grid:

```js
var mongoose = require('mongoose');
var Grid = require('gridfs-stream');
Grid.mongo = mongoose.mongo;

var conn = mongoose.createConnection(..);
conn.once('open', function () {
  var gfs = Grid(conn.db);

How to use mongoose.Error:

31
32
33
34
35
36
37
38
39
40
41
app.use((error, req, res, next) => {
  console.error(error);


  if (error instanceof mongoose.Error.ValidationError) {
    error = createError(StatusCodes.BAD_REQUEST, error);
  } else if (error instanceof mongoose.Error.CastError) {
    error = createError(StatusCodes.NOT_FOUND, 'Resource not found');
  } else if (error.message.includes('E11000')) {
    error = createError(StatusCodes.BAD_REQUEST, 'Already exists');
  } else if (error instanceof jwt.JsonWebTokenError) {

How to use mongoose.Mongoose:

10
11
12
13
14
15
16
17
18
19
it('return valid config', () => {
    let config = {
        consumerConstructors: [
            function() {}
        ],
        mongoose: new Mongoose('http://foo.bar/database'),
        mongoosePrefix: 'prefix-',
        processorConfigs: {
            merge: {
                getProvider,

How to use mongoose.set:

29
30
31
32
33
34
35
36
37
38
    // bufferMaxEntries: 0,
    // useFindAndModify: true,
    // useCreateIndex: true
  };

  mongoose.set('strictQuery', true);
  cached.promise = mongoose.connect(MONGO_URI, opts).then((mongoose) => {
    return mongoose;
  });
}

How to use mongoose.SchemaTypes:

4
5
6
7
8
9
10
11
12
13
14
 * Defines the schema of the payment resource to be stored in the DB
 */
const paymentSchema = new mongoose.Schema({


    bookingId: {
        type: mongoose.SchemaTypes.ObjectId,
        required: true,
        ref : "Booking"
    },
    amount: {

How to use mongoose.createConnection:

55
56
57
58
59
60
61
62
63
64
  connectionString,
  _.cloneDeep(gooseOpt)
);
this.db.on('error', handleDbError);

this.oplogDB = mongoose.createConnection(
  oplogConnectionString,
  _.cloneDeep(gooseOpt)
);
this.oplogDB.on('error', handleDbError);

How to use mongoose.connect:

41
42
43
44
45
46
47
48
49
```

3、 使用"mongoose"连接数据库

```
var db = mongoose.connect("mongodb://user:pass@ip:port/database");
```

说明

How to use mongoose.default:

34
35
36
37
38
39
    created: Number,
    private: Boolean,
    owner: String,
    description: String
});
exports.default = mongoose_1.default.model('Playlists', PlaylistSchema);

How to use mongoose.connection:

50
51
52
53
54
55
56
57
58
        result: "1-0"});

    g1.save(function(err) {});
    g2.save(function(err) {});

    mongoose.connection.close();
});

/* Init elastic search server */

How to use mongoose.Types:

76
77
78
79
80
81
82
83
84
85
      message,
      meta
    },
    // parse `user` from `meta` object if this was associated with a specific user
    meta && meta.user && meta.user.id
      ? { user: new mongoose.Types.ObjectId(meta.user.id) }
      : {}
  )
)
  .then((log) => logger.info('log created', { log, ignore_hook: true }))

How to use mongoose.Schema:

3
4
5
6
7
8
9
10
11
12
const { isEmail } = require('validator');

// <https://github.com/Automattic/mongoose/issues/5534>
mongoose.Error.messages = require('@ladjs/mongoose-error-messages');

const UpgradeReminders = new mongoose.Schema({
  // this is the FQDN that the upgrade is regarding
  domain: {
    type: String,
    required: true,

How to use mongoose.model:

31
32
33
34
35
36
37
38
39
40
  id: String, // Base16 of created.getTime()
  _discussionId: Schema.Types.ObjectId,
  _authorId: Schema.Types.ObjectId
});

var Comment = mongoose.model('Comment', commentSchema);

Comment.syncIndexes(function () {
  Comment.collection.getIndexes({
    full: true