javascript [猫鼬片段]猫鼬#mongoose的提示

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript [猫鼬片段]猫鼬#mongoose的提示相关的知识,希望对你有一定的参考价值。

userSchema.pre("save", function() {
  if (!this.createdOn) {
    this.createdOn = new Date().toString();
    this.modifiedOn = new Date().toString();
  } else {
    this.modifiedOn = new Date().toString();
  }
});
// Aggregation/populate setup:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const personSchema = Schema({
  _id: Schema.Types.ObjectId,
  name: String,
  age: Number,
  stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

const storySchema = Schema({
  author: { type: Schema.Types.ObjectId, ref: 'Person' },
  title: String,
  fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});

const Story = mongoose.model('Story', storySchema);
const Person = mongoose.model('Person', personSchema);

// Population:

// return everything

await Story.
  findOne({ title: 'Casino Royale' }).
  populate('author')
 
// return only name

Story.
  findOne({ title: /casino royale/i }).
  populate('author', 'name'). // only return the Persons name

// populate multiple paths:

Story.
  find(...).
  populate('fans').
  populate('author')

// other options

Story.
  find(...).
  populate({
    path: 'fans',
    match: { age: { $gte: 21 }},
    // Explicitly exclude `_id`, see http://bit.ly/2aEfTdB
    select: 'name -_id',
    options: { limit: 5 }
  }).
var Person = mongoose.model('Person', yourSchema);

// find each person with a last name matching 'Ghost', selecting the `name` and `occupation` fields
Person.findOne({ 'name.last': 'Ghost' }, 'name occupation', function (err, person) {
  if (err) return handleError(err);
  // Prints "Space Ghost is a talk show host".
  console.log('%s %s is a %s.', person.name.first, person.name.last,
    person.occupation);
});

// multi query:

Person.
  find({
    occupation: /host/,
    'name.last': 'Ghost',
    age: { $gt: 17, $lt: 66 },
    likes: { $in: ['vaporizing', 'talking'] }
  }).
  limit(10).
  sort({ occupation: -1 }).
  select({ name: 1, occupation: 1 }).
  exec(callback);
// only get 'name' and 'occupatiton'

Person.findOne({ 'name.last': 'Ghost' }, 'name occupation');

以上是关于javascript [猫鼬片段]猫鼬#mongoose的提示的主要内容,如果未能解决你的问题,请参考以下文章

带有打字稿的猫鼬,来自猫鼬的错误“连接”

如何在猫鼬中转换为字符串?

猫鼬填充返回空数组

猫鼬自动增量

摩卡猫鼬错误

猫鼬模式 + nodejs