日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

踩坑解決mongoose對已經(jīng)存在的集合查詢,查詢條件不起限制作用的問題

作者:N/Z/R/ 更新時(shí)間: 2022-01-03 編程語言

解決mongoose對已經(jīng)存在的集合查詢,查詢條件不起限制作用的問題

router.post('/api/getDataByName',function(req,res,next) {
	var medicinename = req.body.medicinename;
	var medicinecapital = req.body.medicinecapital
	var medicineid = req.body.medicineid
	
	var mongoose = require('mongoose');
	const DB_URL="mongodb://localhost:27017/中醫(yī)藥數(shù)據(jù)庫"
	mongoose.connect(DB_URL)
	var date = new Date()
	const schema = mongoose.Schema();
	const collection = mongoose.model(date,schema,medicinecapital);//最后一個(gè)參數(shù)是集合的名字
	
	// 模糊查詢測試
	// var key = '桉油'
	// const reg = new RegExp(key, '桉油')
	collection.findOne({'藥名': '不灰木'}).then(function(info) {
		console.log(info)
	})

目的是查詢藥名為不灰木的數(shù)據(jù),該數(shù)據(jù)存在數(shù)據(jù)庫中但是執(zhí)行后發(fā)現(xiàn)查詢返回的值是該集合中的第一條數(shù)據(jù)。限制條件不起任何作用。

若使用find()函數(shù)進(jìn)行查詢,限制條件不變但是卻返回了該集合中的所有數(shù)據(jù),限制條件同樣不起任何作用。

解決方案如下:

定義schema的時(shí)候不能定義為空值,下面的這種寫法雖然沒有報(bào)錯(cuò),但是無法通過其他的屬性查詢數(shù)據(jù),只能使用_id查詢數(shù)據(jù)才會(huì)發(fā)揮作用。

const schema = mongoose.Schema({});

經(jīng)過實(shí)驗(yàn),需要在定義的時(shí)候添加一些屬性(一個(gè)或者多個(gè)都行),因?yàn)樵摷现械臄?shù)據(jù)都有的一個(gè)屬性是”藥名“,因此我便把”藥名“定義,至于其他屬性是否一定也要定義,在這里,你定義一個(gè)屬性,如果一條數(shù)據(jù)里面有其他多個(gè)屬性也是能正常查詢的,只要有一個(gè)就行,沒必要都定義一遍。

修改后如下:

const schema = new mongoose.Schema({
	'藥名':{
        type: String,
        required: true
    }
});

修改后再通過”藥名“進(jìn)行查詢就可以咯!!!

	var medicinename = req.body.medicinename;
	var medicinecapital = req.body.medicinecapital
	var medicineid = req.body.medicineid
	var date = new Date()

	const collection = mongoose.model(date,schema,medicinecapital);//最后一個(gè)參數(shù)是集合的名字
	
	collection.findOne({
		藥名: "伯樂樹"
	}).then(function(info) {
		console.log(info)
	})

在這里插入圖片描述
建議大家使用已存在的集合時(shí)最好也要手動(dòng)在schema中添加幾個(gè)屬性。

原文鏈接:https://blog.csdn.net/qq_45955883/article/details/122109360

欄目分類
最近更新