第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

MongooseJS - 插入子文檔而不驗(yàn)證文檔

MongooseJS - 插入子文檔而不驗(yàn)證文檔

瀟瀟雨雨 2023-09-07 16:07:12
我使用 Mongoose 和 Javascript (NodeJS) 來(lái)讀取/寫入 MongoDB。我有一個(gè)文檔(父文檔),其中有一堆子文檔(子文檔)。我的文檔和子文檔都在其模型中定義了驗(yàn)證(required: true以及驗(yàn)證用戶是否將文本放入字段的函數(shù))。當(dāng)嘗試將新的子文檔推送到數(shù)據(jù)庫(kù)時(shí),Mongoose 拒絕我的推送,因?yàn)槲臋n驗(yàn)證失敗。這讓我很困惑,因?yàn)槲也](méi)有嘗試使用子文檔創(chuàng)建新文檔,我只是嘗試將新的子文檔推送到現(xiàn)有文檔中。這是我的(示例)貓鼬模型:const mongoose = require('mongoose');const requiredStringValidator = [  (val) => {    const testVal = val.trim();    return testVal.length > 0;  },  // Custom error text  'Please supply a value for {PATH}',];const childrenSchema = new mongoose.Schema({  childId: {    type: mongoose.Schema.Types.ObjectId,  },  firstName: {    type: String,    required: true,    validate: requiredStringValidator,  },  lastName: {    type: String,    required: true,    validate: requiredStringValidator,  },  birthday: {    type: Date,    required: true,  },});const parentSchema = new mongoose.Schema(  {    parentId: {      type: mongoose.Schema.Types.ObjectId,    },    firstName: {      type: String,      required: true,      validate: requiredStringValidator,    },    lastName: {      type: String,      required: true,      validate: requiredStringValidator,    },    children: [childrenSchema],  },  { collection: 'parentsjustdontunderstand' },);我可以通過(guò)以下 MongoDB 命令成功地將新的子子文檔推送到父文檔中:db.parentsjustdontunderstand.update({    firstName: 'Willard'}, {    $push: {        children: {    "firstName": "Will",    "lastName": "Smith",    "birthday": "9/25/1968"        }    }});但是,當(dāng)我按照 Mongoose 文檔添加子文檔到數(shù)組并嘗試通過(guò) Mongoose 添加它時(shí),它失敗了。出于測(cè)試目的,我使用 Postman 并對(duì)端點(diǎn)執(zhí)行 PUT 請(qǐng)求。以下是req.body:{    "firstName": "Will",    "lastName": "Smith",    "birthday": "9/25/1968"}我的代碼是:const { Parent } = require('parentsModel');const parent = new Parent();parent.children.push(req.body);parent.save();我得到的回報(bào)是:ValidationError: Parent validation failed: firstName: Path `firstName` is required...`它列出了父文檔的所有驗(yàn)證要求。我可以為我做錯(cuò)的事情提供一些幫助。作為記錄,我在 Stackoverflow 上查看了這個(gè)答案:Push items into mongo array via mongoose,但我看到的大多數(shù)示例都沒(méi)有顯示或討論其 Mongoose 模型中的驗(yàn)證。
查看完整描述

2 回答

?
湖上湖

TA貢獻(xiàn)2003條經(jīng)驗(yàn) 獲得超2個(gè)贊


這是不正確的:


const child = {

? children: {

? ? ? "firstName": "Will",

? ? ? "lastName": "Smith",

? ? ? "birthday": "9/25/1968"

? }

}

這是正確的:


const child = {

? ? "firstName": "Will",

? ? "lastName": "Smith",

? ? "birthday": "9/25/1968"

}

該記錄被插入數(shù)據(jù)庫(kù)并保存,但由于我將其作為 PUT 請(qǐng)求啟動(dòng),因此在使用HTTP 200 OK. 下面是整個(gè)解決方案的正確代碼,但是請(qǐng)記住,該res.status代碼僅在這種情況下才是必需的,因?yàn)槲沂峭ㄟ^(guò) PUT 請(qǐng)求來(lái)模仿代碼的。


貓鼬型號(hào):


const mongoose = require('mongoose');


const requiredStringValidator = [

? (val) => {

? ? const testVal = val.trim();

? ? return testVal.length > 0;

? },

? // Custom error text

? 'Please supply a value for {PATH}',

];

const childrenSchema = new mongoose.Schema({

? childId: {

? ? type: mongoose.Schema.Types.ObjectId,

? },

? firstName: {

? ? type: String,

? ? required: true,

? ? validate: requiredStringValidator,

? },

? lastName: {

? ? type: String,

? ? required: true,

? ? validate: requiredStringValidator,

? },

? birthday: {

? ? type: Date,

? ? required: true,

? },

});

const parentSchema = new mongoose.Schema(

? {

? ? parentId: {

? ? ? type: mongoose.Schema.Types.ObjectId,

? ? },

? ? firstName: {

? ? ? type: String,

? ? ? required: true,

? ? ? validate: requiredStringValidator,

? ? },

? ? lastName: {

? ? ? type: String,

? ? ? required: true,

? ? ? validate: requiredStringValidator,

? ? },

? ? children: [childrenSchema],

? },

? { collection: 'parentsjustdontunderstand' },

);

const mongooseModels = {

? Parent: mongoose.model('Parent', parentSchema),

? Children: mongoose.model('Children', childrenSchema),

};

module.exports = mongooseModels;

以下是req.body:


{

? ? "firstName": "Will",

? ? "lastName": "Smith",

? ? "birthday": "9/25/1968"

}

代碼是:


const { Parent } = require('parentsModel');

const parent = await Parent.findOne({firstName: 'Willard'});

parent.children.push(req.body);

parent.save((err, doc) => {

? if (err) {

? ? res.status(500).json({

? ? ? message: 'Error finding active projects',

? ? ? error: err,

? ? });

? } else {

? ? res.status(200).json(doc);

? }

});


查看完整回答
反對(duì) 回復(fù) 2023-09-07
?
holdtom

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個(gè)贊

您可以使用 mongo 查詢將子級(jí)推送到父級(jí),因?yàn)樵?中update,第一個(gè)對(duì)象是查找推送的文檔。


語(yǔ)法如下:update({query},{update},{options})。因此,您正在尋找包含firstName: 'Willard'子項(xiàng)的文檔并將其添加到其中。


這里一切正常,所有字段都存在,父級(jí)存在于集合中,所以沒(méi)有問(wèn)題。


但使用

const parent = new Parent();

parent.children.push(req.body);

parent.save();

您的父對(duì)象是空的(除非構(gòu)造函數(shù)填充所有字段,但我認(rèn)為這不是一個(gè)好主意)。


如果你嘗試這樣做:


var parent = await model.findOne({firstName: 'Willard'})

parent.children.push(req.body);

parent.save();

然后應(yīng)該可以工作。


在本例中,對(duì)象parent是從集合中檢索的,因此它包含所有必需的字段。


我將進(jìn)行編輯以更好地解釋為什么這兩個(gè)查詢不相同。


基本上,您嘗試保存的子對(duì)象的結(jié)構(gòu)不同db.collection.update。請(qǐng)注意,您創(chuàng)建的要插入到集合中的對(duì)象child只有一個(gè)名為 的屬性children。它不具有必要的屬性,例如firstName...


我將使用純 JS 來(lái)查看console.log()輸出是什么并查看差異。


你的 mongo 查詢推送一個(gè)像這樣的對(duì)象(翻譯成 js 語(yǔ)言):


var array = []

array.push(

    children = {

        "firstName": "Will",

        "lastName": "Smith",

        "birthday": "9/25/1968"

    }

)


console.log(array)


但您正在以這種方式創(chuàng)建對(duì)象:


const child = {

  children: {

      "firstName": "Will",

      "lastName": "Smith",

      "birthday": "9/25/1968"

  }

}


console.log(child)


現(xiàn)在你看出區(qū)別了嗎?一個(gè)對(duì)象是子對(duì)象本身,另一個(gè)對(duì)象具有屬性children 和必要的字段。


那么讓我們將這兩段代碼組合起來(lái):


const child = {

  children: {

      "firstName": "Will",

      "lastName": "Smith",

      "birthday": "9/25/1968"

  }

}


const children = {

        "firstName": "Will",

        "lastName": "Smith",

        "birthday": "9/25/1968"

    }


var array = [child,children]

console.log(array)


因此,對(duì)于您的代碼,如果您使用:


parent.children.push(child.children);

parent.save();

應(yīng)該有效。children但是,最好的方法不是在里面創(chuàng)建對(duì)象const child


嘗試使用:


const child = {

  "firstName": "Will",

  "lastName": "Smith",

  "birthday": "9/25/1968"

}

parent.children.push(child);

parent.save();


查看完整回答
反對(duì) 回復(fù) 2023-09-07
  • 2 回答
  • 0 關(guān)注
  • 128 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)