标签: mongoose-schema

猫鼬动态枚举值

我的猫鼬架构如下。

'use strict';

var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

var UserSchema = new Schema({
  role: {
    type: String,
    enum: ['user', 'admin']
  }
});

mongoose.model('User', UserSchema);
Run Code Online (Sandbox Code Playgroud)

我想从数据库动态设置角色枚举值而不是硬编码,我该怎么做?

enums mongoose node.js mongoose-schema

4
推荐指数
1
解决办法
2876
查看次数

如何从猫鼬获取定义的索引

我一直在尝试找出已经通过 MongoDB 手动创建的索引(我已经通过 mongobooster 为两个字段创建了 2d 球体索引,并通过定义它通过模式创建了一个)。现在,如果我在 mongodbooster 中运行此查询

db.collectionname.getIndexes(); 
Run Code Online (Sandbox Code Playgroud)

它给我带来了 3 个带有 name.key 的文档以及我使用过的索引。我想在猫鼬中执行相同的操作,但找不到相同的等效查询。我试过这个

const indexes = OrderSchema.indexes();
console.log('index:', indexes);
Run Code Online (Sandbox Code Playgroud)

但它只给了我一个索引,我在模式中定义了 _id 我还需要两个其他字段,其中包含 2d-sphere 索引,我怎么才能得到它。我在这里试图实现的是,如果已经创建了 2d 球体索引,则不要创建索引,否则创建一个索引,这正是我在这里试图实现的。任何帮助表示赞赏谢谢

mongoose mongodb node.js mongoose-schema

4
推荐指数
1
解决办法
7704
查看次数

mongodb模式如何设置子文档数组的默认值?

示例我有这个架构。

{
  field1: {
    type: String,
    trim: true
  },
  field2: [{
    subField1: {
      type: String,
    },
    subField2: {
      type: Number,
      default: 0
    }
  }]
}
Run Code Online (Sandbox Code Playgroud)

field2如果我刚刚field1在文档插入中提供了,我应该如何设置模式的默认值?

示例 如果我只是插入{field1: "sample string data"},则 上的值field2是一个空数组。

arrays mongodb mongoose-schema

4
推荐指数
1
解决办法
5297
查看次数

mongoose - 如何在 getter 中获取对象而不是对象引用?

我在 Node.js 中使用 mongoose 创建了一个 API。我将我的数据保存在一个集合 Transactions 中,它提供了来自其他集合对象的一些引用:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const transactionSchema = new Schema({
  status: String,
  _user: { type: Schema.Types.ObjectId, ref: 'User' },
  _borne: { type: Schema.Types.ObjectId, ref: 'Borne' },
  createdAt: Date,
  updatedAt: Date
});
Run Code Online (Sandbox Code Playgroud)

当我查询交易时,我会得到 Borne 对象而不是它的 id,因为它保存在我的数据库中。我不直接将它保存为 Borne 对象,因为我的 Borne(或 User)对象中可能会出现一些更改,我希望将其保存在每个 Transaction 对象上。

所以我尝试使用虚拟或路径(覆盖),但它不会改变我的输出,我也不知道这是否是正确的方法:

// In this example, I try to change the status output by "new status" to test if it works, and it doesn't
transactionSchema.path('status')
    .get(function(value) { …
Run Code Online (Sandbox Code Playgroud)

javascript mongoose mongodb node.js mongoose-schema

4
推荐指数
1
解决办法
6921
查看次数

模式验证中所需的 Mongoose 数组不起作用

在我的架构中,我需要有一个属性,它是一个必须始终不为空且不为未定义的数组。

所以我定义了它是必需的,但是验证并没有像我预期的那样工作,因为如果我省略了这个属性,就不会抛出任何错误。

在简单属性(不是数组)的情况下,这按我的预期工作

const nodeSchema = new Schema({
    address: { type: String, required: true },
    outputs: { type: [String], required: true }
})
Run Code Online (Sandbox Code Playgroud)

mongoose mongodb mongoose-schema

4
推荐指数
2
解决办法
1323
查看次数

如何在猫鼬中获取模式的父级?

我正在编写一个 Node.js 应用程序,它使用 Mongoose 作为 ORM。

我有一个名为 Event 的模型和一个名为 Participant 的模式,它作为子文档存储在我的 Event 模式中。问题是,我需要实现一个应该访问父数据的方法。并且没有关于此的文档(或者我找不到任何文档)。如何从其孩子访问父母的数据?

我见过$parent几次的用法,但它对我不起作用。我也播种了 的用法this.parent(),但这会导致RangeError: Maximum call stack size exceeded我的示例。

这是我的代码示例:

const Participant = mongoose.Schema({
// description
});

const eventSchema = mongoose.Schema({
    applications: [Participant],
    // description
});

const Event = mongoose.model('Event', eventSchema);

Participant.virtual('url').get(function url() {
    // the next line causes a crash with 'Cannot get "id" of undefined'
    return `/${this.$parent.id}/participants/${this.id}`; // what should I do instead?
});
Run Code Online (Sandbox Code Playgroud)

mongoose node.js mongoose-schema

4
推荐指数
1
解决办法
2692
查看次数

Mongoose Schema 静态与方法

在猫鼬模式中,我们可以将方法创建为两种方式SchemaName.methods.fuctionNameSchemaName.statics.functionName。静态更容易使用我只需要调用ModelName.Fuction。方法需要创建对象才能使用。我的问题是它们之间有什么不同。静态方法的优缺点是什么。什么时候应该使用静态,什么时候应该使用方法

// Users.js
UserSchema.statics.findUserStatics = async function(mail) {
    var findUser = await User.findOne({ mail: mail })
    return findUser
}

UserSchema.methods.findUserMethods = async function(mail) {
    var findUser = await User.findOne({ mail: mail })
    return findUser
}

// router.js

const { User } = require('./../models/Users')
router.post('/findbyStatics', async (req, res) => {
    try {
        var result = await User.findUserbyStatics(req.body.mail);
        res.status(200).send(result)
    } catch (e) {
        res.status(400).send(e.message)
    }
})

router.post('/findbyMethods', async …
Run Code Online (Sandbox Code Playgroud)

mongoose-schema

4
推荐指数
1
解决办法
1147
查看次数

在猫鼬中创建新文档时可以添加新属性吗?

我有这个架构(例如):

var WordSchema = new Schema({
    word: {
        type: String
    }
});
module.exports = mongoose.model('Word', WordSchema);
Run Code Online (Sandbox Code Playgroud)

在猫鼬中创建新文档时如何添加新属性?像这样的东西:

let Word = require("../models/word");
let initWord = "hello";
word = new Word({
   word: initWord,
   length: initWord.length
});

word.save(function(error) {
  if (error) {  
    //some code              
  } else {
    //some code              
  }
});
Run Code Online (Sandbox Code Playgroud)

但这不起作用

mongoose mongodb node.js mongoose-schema

4
推荐指数
1
解决办法
2048
查看次数

如何在 Mongoose 中定义除 _id 以外的其他主键?

我想用不是_id. 该文档说它只允许_id在子文档中将架构选项标志设置为 false。另外,我希望主键是 aString而不是ObjectId. 这可能吗?

使用二级索引是一种选择,但不是一个很好的选择,因为我希望主键具有正确的名称。当我不需要时,我也不想摆弄两个不同的索引。

这设置documentId为二级索引,但这使得主键无用,因为我只想选择 bydocumentId而不是_id最终自动设置的任何内容。

const DocumentSchema = new Schema({
  documentId: { type: String, index: true }
})
Run Code Online (Sandbox Code Playgroud)

我想做类似的事情

const DocumentSchema = new Schema({
  documentId: String
})
Run Code Online (Sandbox Code Playgroud)

然后告诉它用documentId作主键。

说明:我特别不想将_id用作键,因为它的名称无用,而我想用documentId作主键。

javascript mongoose mongodb node.js mongoose-schema

4
推荐指数
1
解决办法
6548
查看次数

Node JS mongoose 创建博客文章评论系统

我正在尝试用猫鼬和快递建立一个带有评论系统的简单博客。这里没有创建和发布博客的问题,每个帖子都可以正确显示。但是,有一些与评论和每个博客相关的问题。评论和博客帖子之间的关系是通过在帖子架构中应用 mongoose.Schema.Types.ObjectId 来建立的,并且已经创建了评论来存储评论 id 数组。我认为架构结构是正确的,我的路由代码中可能存在一些问题,请帮助,谢谢。

    // Post Schema
    const mongoose = require('mongoose');

    const postSchema = new mongoose.Schema({
      title: {
       type: String,
       trim: true,
       required: true
     },
       text: {
       type: String,
       trim: true,
       required: true
     },
      date: {
       type: Date,
       default: Date.now
     },
      comments: [{
       type: mongoose.Schema.Types.ObjectId,
       ref: 'Comment'
      }]
    })

    postSchema.virtual('url').get(function(){
      return '/post/' + this._id
     })

    module.exports = mongoose.model('Post', postSchema); 


     // Comment Schema 
     
     const mongoose = require('mongoose');

     const commentSchema = new mongoose.Schema({
        text: {
         type: String,
         trim: true,
         required: true …
Run Code Online (Sandbox Code Playgroud)

schema mongoose mongodb node.js mongoose-schema

4
推荐指数
1
解决办法
1006
查看次数

标签 统计

mongoose-schema ×10

mongoose ×8

mongodb ×7

node.js ×7

javascript ×2

arrays ×1

enums ×1

schema ×1