嵌入式文档的Mongoose.js模式选项不起作用 [英] Mongoose.js schema options for embedded documents are not working

查看:47
本文介绍了嵌入式文档的Mongoose.js模式选项不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对node.js和mongoose非常陌生.我的架构如下.

I am very new to node.js and mongoose. I have schema as follows.

var sub = Schema({"title": {type: String, required: true, trim: true, unique: true},
                  "uniqueId": Schema.ObjectId}

var main = Schema({"name": {type: String, required: true, index: { unique: true, dropDups: true},
                  "subs": [sub]}

这正在工作.插入文件.订阅已添加.问题如下.

This is working. Documents are inserted. Subs are getting added. Problems are as follows.

我在这里期望的是将新的sub添加到main中.它将检查标题是否存在,如果不存在则抛出异常.它将检查标题是否唯一.另外,它将自己将对象ID分配给uniqueId字段.但是,这没有发生.它不检查标题是否存在和唯一.另外,没有将objectId分配给uniqueId,而是将其分配给_id.

What I was expecting here is when I add new sub into main. It will check the title is present or not and throw exception if not. It will check if title is unique or not. Also, it will assign the object id to uniqueId field on its own. But this is not happening. It is not checking if title is present and unique. Also, objectId is not getting assigned to uniqueId, it is assigned to _id instead.

这是将sub添加到main中的代码.

Here is the code for adding the sub into main.

MainModel.findByIdAndUpdate(
        request["_id"], 
        {$push: {subs: {"title": "New title"}}}, {}, function(err, doc) {
            console.log(err);
            console.log(doc);
        }
    );

猫鼬将此查询记录为

MainModel.findAndModify({ _id: ObjectId("537caa880519db710d7b5b2a") }) [] { '$push': { subs: { _id: ObjectId("537d6b96f927d6573c6e1044"),  title: 'New title' } } } { upsert: false, new: true }

如果看到ObjectId被分配给_id而不是uniqueId.此外,它不会检查标题是否存在并且是唯一的.

If you see ObjectId is getting assigned to _id and not uniqueId. Also, it does not check if title is present and is unique.

也许我这边有个愚蠢的错误.我在这里想念什么.

May be there is silly mistake on my side. What am I missing here.

推荐答案

当使用任何findAndModify帮助器时,将不应用默认值,设置器,验证器和中间件.请在此处 http://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate

Defaults, setters, validators and middleware are not applied when any findAndModify helper is used. See here http://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate

这篇关于嵌入式文档的Mongoose.js模式选项不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆