标签: mongoose-schema

猫鼬:我们可以将引用对象填充到别名/虚拟属性吗?

我正在寻找一种使用猫鼬填充到别名/虚拟属性的方法?

就目前而言,猫鼬的种群是在引用属性中添加更多字段(通常是身份密钥)。我想保留原始属性,然后将引用的数据填充到其他属性。

例如:似乎我们需要更多的架构选项

profile_id: { type: mongoose.Schema.Types.ObjectId, ref: 'profiles', populateTo: 'profile' }
Run Code Online (Sandbox Code Playgroud)

结果返回应包含两个属性:profile_idprofile

经过搜索之后,我在github上发现了这个问题:( https://github.com/Automattic/mongoose/issues/3225

mongoose mongoose-populate mongoose-schema

5
推荐指数
1
解决办法
1078
查看次数

猫鼬承诺错误

这是在添加本机承诺后保存时仍会抛出的错误.

(节点:5604)弃用警告:不推荐使用Mongoose:mpromise(mongoose的默认承诺库),而是插入自己的promise库:http://mongoosejs.com/docs/promises.html

mongoose.Promise = global.Promise;
mongoose.connect('mongodb://127.0.0.1/optimusCP')
    .then(function () {
        console.log('Connected to MONGOD !!');
    }).catch(function (err) {
        console.log('Failed to establish connection with MONGOD !!');
        console.log(err.message);
    });
Run Code Online (Sandbox Code Playgroud)

我试过蓝鸟和q,仍然没有找到解决方案.下面是保存时的代码,显示以下弃用警告..

var user = new User();
        user.email = req.body.email;
        user.password = hash;
        user.save()
            .then(function (user) {
                console.log(user);
            })
            .catch(function (err) {
                console.log(err);
            });
Run Code Online (Sandbox Code Playgroud)

这个错误发生在mongoose的新版本4.8.1,但在4.7.6 mongoose版本上工作正常.

mongoose mongodb node.js promise mongoose-schema

5
推荐指数
1
解决办法
5872
查看次数

猫鼬复合索引创建字段顺序

我对mongodb中的复合索引创建有疑问:说我想创建此复合索引:

cSchema.index({account:1, authorization: 1, c_type: 1});
Run Code Online (Sandbox Code Playgroud)

问题是,javascript不能保证字典的顺序,所以我不能确定复合索引是否符合我想要的顺序。

我如何确保它确实{account:1, authorization:1, c_type:1}按顺序排列?

谢谢 !

mongoose mongodb node.js mongoose-schema

5
推荐指数
1
解决办法
370
查看次数

Mongo / Mongoose:Mongoose是否自动在ObjectId类型上创建索引?

我可能在mongo索引文档或mongoose文档中错过了这一点。

假设我有这样的猫鼬模式:

const SomeEntity = new Schema({
  foo:  { type: String, required: true },
  bar   { type: Schema.ObjectId, ref: 'Bar' }
});
Run Code Online (Sandbox Code Playgroud)

我应该在字段上创建索引bar还是mongo会自动解决这个问题?

换句话说,mongo是否会自动为ObjectId类型创建索引?

javascript mongoose mongodb node.js mongoose-schema

5
推荐指数
1
解决办法
1134
查看次数

基于 Mongoose 中其他两个字段的第三个字段的计算

我在 Mongoose 模型上有 2 个字段:totalAttempts 和totalRight。我打算根据它们计算准确性。

totalAttempts: {
    type: Number,
    default: 1
},
totalRight: { 
    type: Number,
    default: 1
}
Run Code Online (Sandbox Code Playgroud)

这就是我所做的[它不起作用]

 accuracy:{
     type:Number,
     required:function() {return (this.totalRight/this.totalAttempts*100).toFixed(2)}
}
Run Code Online (Sandbox Code Playgroud)

另外,如果我不为准确度设置默认值,我会收到错误:

ERROR; While creating new question ..ValidationError: Path `accuracy` is require                      d.

events.js:163
Run Code Online (Sandbox Code Playgroud)

实现这一目标的正确方法是什么?我已经有了一个可行的解决方案,可以在每次用户请求该模型时获取totalAttempts 和totalRight。但我想保存该计算并将信息存储在我的数据库中。

mongoose mongodb node.js mongoose-schema

5
推荐指数
1
解决办法
3168
查看次数

每次我使用预先保存的钩子保存时,猫鼬都会更改密码

我正在使用带有bcrypt的预保存钩子来加密系统上的密码。创建或更改密码时,它可以正常工作。问题在于,每次我更改并保存其他字段(例如电子邮件)时,它似乎都重新加密了密码。

用代码可能更容易解释。这是模型:

const UserSchema = new Schema({
    email: {
        type: String,
        required: true,
        lowercase: true,
        unique: true,
        trim: true
    },
    password: {
        type: String,
        required: true
    }
})
Run Code Online (Sandbox Code Playgroud)

和钩子:

UserSchema.pre('save', function(next){
    const user = this;
    console.log(user);
    bcrypt.genSalt(10, function(err, salt){
        if (err){ return next(err) }

        bcrypt.hash(user.password, salt, null, function(err, hash){
            if(err){return next(err)}

            user.password = hash;
            next();
        })
    })
});
Run Code Online (Sandbox Code Playgroud)

这是我的更新电子邮件地址的代码:

module.exports = function(req, res){
    User.findOne({ _id: req.body.user}, function(err, doc){
        if(err){
            console.log(err);
            return;
        }

        doc.email = req.body.data;
        doc.save(function(err, returnData){
            if (err){
                console.log(err); …
Run Code Online (Sandbox Code Playgroud)

javascript mongoose node.js mongoose-schema

5
推荐指数
1
解决办法
976
查看次数

如何声明与 ESLint 一起使用的 mongoose 静态方法

使用 Mongoose ORM 进行 MongoDB

我声明了一个猫鼬静态方法,如下所示:

ConvoDataSchema.statics.randomItem = async function () { ... }
Run Code Online (Sandbox Code Playgroud)

然后用它创建一个模型

const ConvoData = mongoose.model('ConvoData', ConvoDataSchema)
Run Code Online (Sandbox Code Playgroud)

但后来当我想调用该方法时:

let convoData = await ConvoData.randomItem()
Run Code Online (Sandbox Code Playgroud)

我的 linter 不知道ConvoDataMongoose 已经修补了这个神奇的方法。

我如何声明这些方法,以便 Linter (TSLint / VSCode Intellisense) 可以正确发现这些方法?

mongoose node.js eslint mongoose-schema

5
推荐指数
1
解决办法
814
查看次数

Mongoose 和引用 UUID 数组不转换

使用 mongoose-uuid 库时,我可以为模式设置 UUID 类型,因此当我读取数据时,它采用字符串 (utf-8) 格式,而当我保存数据时,它采用 UUID ObjectID BSON 类型 4 格式。这对于我的架构中的顶级或平面直接值和引用定义非常有效。但是,当我在架构中的引用数组中有 UUID 时,该数组会正确保存到数据库,但是当它呈现时,它是原始类型。根据下面的示例,您可以看到scope_id 以正确的格式显示,但权利却不然。

以下是我正在使用的版本: mongoose-uuid - 2.3.0 mongoose - 5.5.11

我尝试通过更改 getter 和转换值来修改库(mongoose-uuid),但是,当我这样做时,它在呈现时有效,但在保存到数据库时失败。这很可能是由于该值在保存到数据库之前进行了转换或转换。

这是一个示例架构

    {
      "code": {
        "type": String,
        "required": true
      }, 
      "scope_id": {
        "type": mongoose.Types.UUID,
        "ref": "scopes"
      },
      "entitlements": [{
        "type": mongoose.Types.UUID,
        "ref": "entitlements"
      }]
    }

Run Code Online (Sandbox Code Playgroud)

实际响应示例

{
    "entitlements": [
        "zMihi1BKRomM1Q41p7hgLA==",
        "ztOYL7n1RoGA6aoc0TcqoQ=="
    ],
    "code": "APPUSR",
    "scope_id": "b8f80c82-8325-4ffd-bfd7-e373a90e7c45",
    "id": "32e79061-e531-45ad-b934-56811e2ad713"
}
Run Code Online (Sandbox Code Playgroud)

预期反应

{
    "entitlements": [
        "ccc8a18b-504a-4689-8cd5-0e35a7b8602c",
        "ced3982f-b9f5-4681-80e9-aa1cd1372aa1"
    ],
    "code": "APPUSR",
    "scope_id": "b8f80c82-8325-4ffd-bfd7-e373a90e7c45",
    "id": "32e79061-e531-45ad-b934-56811e2ad713"
}
Run Code Online (Sandbox Code Playgroud)

uuid mongoose express mongoose-schema

5
推荐指数
1
解决办法
1250
查看次数

在多个微服务上使用猫鼬模式

我的应用程序被分成多个在heroku dynos上运行的微服务(它们无法访问彼此的文件)。有时,有多个微服务与一个集合一起使用。因此,这两个微服务都需要相应的猫鼬模式。

但是,并非两个微服务都需要完整架构。例如,微服务 A 需要完整架构,而微服务 B 仅需要该架构的几个字段。

微服务 A 内的示例架构:

var AccountSchema = mongoose.Schema({
    email: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    phone: { type: String, required: true, unique: true },
    forename: { type: String, required: true },
    surname: { type: String, required: true },
    middleInitals: { type: String, required: false },
    failedLoginAttempts: { type: Number, required: true, default: 0 },
    lockUntil: { type: Number },
    createdAt: …
Run Code Online (Sandbox Code Playgroud)

mongoose mongodb node.js microservices mongoose-schema

5
推荐指数
1
解决办法
1826
查看次数

Mongoose 用户、角色和权限

我对 NoSQL/Mongo/Mongoose 很陌生,我正在尝试确定设置模式的最佳方法。这是我所拥有的:

const UserSchema = new mongoose.Schema(
  {
    email: {
      type: String,
      required: true
    },
    password: {
      type: String,
      required: true,
      minlength: 6,
      select: false,
    },
    roles: [
      {
        type: mongoose.Schema.ObjectId,
        ref: 'Role',
      },
    ],
  }
);
Run Code Online (Sandbox Code Playgroud)
const RoleSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      unique: true,
    },
    description: {
      type: String,
    },
    permissions: [
      {
        type: mongoose.Schema.ObjectId,
        ref: 'Permission',
      },
    ],
  }
);
Run Code Online (Sandbox Code Playgroud)
const PermissionSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: …
Run Code Online (Sandbox Code Playgroud)

mongoose mongodb node.js express mongoose-schema

5
推荐指数
1
解决办法
6512
查看次数