当我有关系时,我在试图找到查询猫鼬中某些内容的正确方法时遇到了一些困难。
基本上我有一个文档,其 ObjectId 与另一文档相关(如下所示)。
但是当我尝试过滤引用的属性时,没有任何效果了。基本上,问题是这一行“ .where({ "Recipe.Title": new RegExp("*") }) "
// const configs
const config = require('./config');
// mongodb setup
const mongoose = require('mongoose');
mongoose.connect(config.database);
var Schema = mongoose.Schema
// recipe schema
const RecipeSchema = mongoose.Schema({
Title: { type: String },
Description: { type: String },
Complaints: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Complaint' }],
});
const Recipe = mongoose.model('Recipe', RecipeSchema);
// complaint schema
const ComplaintSchema = mongoose.Schema({
Recipe : { type: mongoose.Schema.Types.ObjectId, ref: 'Recipe' },
Message: { type: String }
});
const Complaint = mongoose.model('Complaint', ComplaintSchema);
/*
after inserting some items
*/
Complaint
.find()
.populate("Recipe")
.where({ "Recipe.Title": new RegExp("*") }) // this is not working!
.exec((error, items) => {
items.map((item) => {
console.log(item);
});
});
Run Code Online (Sandbox Code Playgroud)
有人有正确的方法来解决它吗?
(1)new RegExp("*")似乎不是一个有效的正则表达式,因为*它很特殊,意味着重复 0 次或多次,例如,a*表示 0 或多次a。
如果您尝试使用*,则需要转义它:new RegExp('\\*')
(2) 我认为你最好使用匹配(请参阅查询条件和其他选项)。
Complaint.find().populate({
path: "Recipe"
match: {
title: new RegExp('\\*')
}
}).exec(...);
Run Code Online (Sandbox Code Playgroud)
尽管我相信这会引起所有抱怨,并用与正则表达式匹配的食谱来填充这些抱怨。
如果您真的只想抱怨与正则表达式匹配的食谱,那么您最好反其道而行之。
Recipe.find({ title: new RegExp('\\*') }).populate('Complaints').exec(...)
Run Code Online (Sandbox Code Playgroud)
或者使用聚合,您可以使用$lookup加入 Recipes 集合并使用$match来过滤文档。
编辑:我相信会是这样的
Complaint.aggregate([
// join Recipes collection
{
$lookup: {
from: 'Recipes',
localField: 'Recipe',
foreignField: '_id',
as: 'Recipe'
}
},
// convert array of Recipe to object
{
$unwind: '$Recipe'
},
// filter
{
$match: {
'Recipe.title': new RegExp('\\*')
}
}
]).exec(...)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7569 次 |
| 最近记录: |