我正在尝试找到一种方法来修改猫鼬的查询结果。
下面是带柱钩的独立模型
'use strict';
// load the things we need
var mongoose = require('mongoose');
var invoice_db = mongoose.createConnection(config.mongo.url + '/invoiceDB'); //connect to buyer DB
var path = require('path');
// define the schema for our invoice details model
var invoicedetailSchema = new Schema({
//SCHEMA INFO
});
invoicedetailSchema.post('find', function(results){
console.log('POST FIRED')
results = results.filter(function(doc){
return doc.tags.length;
})
})
var InvoiceModel = invoice_db.model('InvoiceDetail', invoicedetailSchema);
// create the model for seller and expose it to our app
promise.promisifyAll(InvoiceModel);
promise.promisifyAll(InvoiceModel.prototype);
module.exports = InvoiceModel;
Run Code Online (Sandbox Code Playgroud)
查找查询工作正常并且帖子正在触发,但结果没有根据帖子挂钩进行过滤。
在返回结果之前我该如何编辑结果。
我有这样的查询:
galleryModel.find({_id: galleryId})
.populate({
model: 'User',
path: 'objectId',
select: 'firstName lastName'
})
Run Code Online (Sandbox Code Playgroud)
的最终响应objectId将如下所示:
objectId: {
...
}
Run Code Online (Sandbox Code Playgroud)
如何user在不更改实际路径的情况下将其更改为响应?
我很大程度上相信这个错误是由于我调用的对象不包含该.populate函数造成的,尽管我不知道如何更改它以使其工作。
首先,这是完整的错误。
TypeError: exam[0].modules[u].topics[i].populate(...).exec is not a function
at /home/ubuntu/workspace/tests/app.js:425:84
at Query.Model.$wrapCallback (/home/ubuntu/workspace/tests/node_modules/mongoose/lib/model.js:3336:16)
at /home/ubuntu/workspace/tests/node_modules/mongoose/node_modules/kareem/index.js:259:21
at /home/ubuntu/workspace/tests/node_modules/mongoose/node_modules/kareem/index.js:127:16
at nextTickCallbackWith0Args (node.js:420:9)
at process._tickCallback (node.js:349:13)
Process exited with code: 1
Run Code Online (Sandbox Code Playgroud)
我指的具体行是exam[0].modules[u].topics[i].populate("questions").exec(function(err,quests)另一行,我认为这里非常重要,这是examBoard.find({name:req.body.examBoardName},function(err,exam)返回exam不包含该.populate函数的行。
我认为这很大程度上是由于我缺乏经验,而不是逻辑错误,但我不确定。
这是包含错误的代码部分。
app.post("/test",function(req,res)
{
console.log("\n\n\n\n")
var time = req.body.time;
var topicName = [req.body.topic1,req.body.topic2,req.body.topic3,req.body.topic4,req.body.topic5];
var topicsArray = [];
examBoard.find({name:req.body.examBoardName},function(err,exam)
{
if(err)
{
console.log(err);
}
else
{
for(var u=0;u<exam[0].modules.length;u++)
{
console.log("exam[0].modules[u]:\n"+exam[0].modules[u]);
console.log("req.body.moduleName:\n"+req.body.moduleName);
if(exam[0].modules[u].name==req.body.moduleName)
{
console.log("topicName[]:\n"+topicName[0]+"\n"+topicName[1]+"\n"+topicName[2]+"\n"+topicName[3]+"\n"+topicName[4]);
for(var i=0;i<exam[0].modules[u].topics.length;i++)
{
console.log("exam[0].modules[u].topics[i].name:\n"+exam[0].modules[u].topics[i].name);
for(var t=0;t<topicName.length;t++)
{
if(exam[0].modules[u].topics[i].name==topicName[t]) …Run Code Online (Sandbox Code Playgroud) 我有一个包含消息的消息集合,模型看起来像这样.
var MessageSchema = new mongoose.Schema({
groupId: { type: Schema.ObjectId, ref: 'Group' },
});
var GroupSchema = new mongoose.Schema({
type: String,
groupMembers: [{ "user": { type: Schema.ObjectId, ref: 'User' } }],
});
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
Message.find({ 'groupId': { $in: groupIds } })
.populate(
{ path: 'groupId', select: 'groupMembers type name level',
populate: { path: 'groupMembers.user', select: 'name _id photo', model: 'User' } })
Run Code Online (Sandbox Code Playgroud)
仅当groupId.type与条件匹配时,如何填充groupMembers.user?
我试过这个但是:-(
{match:"groupId.type":'individual'}
Run Code Online (Sandbox Code Playgroud) 我想通过clientSchema中的属性'token'查询子文档数组.但是我无法填充子文档数组.它总是返回空值.
这就是我的尝试
var performAuthAsync = promise.promisify(performAuth);
var response = {};
performAuthAsync(req).then(function (client) {
sendStatus(res, 200, { "success": "true", "value": client });
}).catch(ApiError, function (e) {
response.error = "true";
response.message = e.message;
if (e.message == "Invalid Authorization" || e.message == "Unauthorized access") {
console.log(e.message);
sendStatus(res, 401, response, req.query.type);
}
else {
sendStatus(res, 500, response, req.query.type);
}
});
Run Code Online (Sandbox Code Playgroud)
PerformAuth方法
function performAuth(req, callback) {
try {
var authHeader = req.headers.authorization;
console.log(authHeader);
//error in req format
if (!authHeader || !authHeader.startsWith("Basic ")) {
console.log("inside fail …Run Code Online (Sandbox Code Playgroud) 说,我有Manager架构:
{
name: { type: String },
clients: [{ type: Mongoose.Schema.ObjectId, ref: 'Client'}]
}
Run Code Online (Sandbox Code Playgroud)
而且,我有Client架构:
{
name : { type String },
cars : [{ type: Mongoose.Schema.ObjectId, ref: 'Car' }],
houses: [{ type: Mongoose.Schema.ObjectId, ref: 'House' }]
}
Run Code Online (Sandbox Code Playgroud)
而且Car,House(它们的结构对此并不重要。如何Client在单个.populate()调用中深度填充多个字段?
我尝试了什么:
Manager.find()
.populate({
path: 'users',
populate: { path: 'cars' },
populate: { path: 'houses' }
});
Run Code Online (Sandbox Code Playgroud)
如果它奏效的话,这会让我真正感到惊讶(因为我覆盖了之前声明的populate传递给.populate()方法的键)。我的示例显然返回了houses每个用户的填充字段-最后一个。老实说,不知道,文档中也没有。甚至支持吗?根据我的示例,我知道它是针对“浅”填充的:
User.populate('cars')
.populate('houses')
Run Code Online (Sandbox Code Playgroud)
那深渊呢?
我先运行聚合管道,然后填充,然后尝试获取特定的数据模型,但现在还不够。
最后所需的结果如下:
[
{
_accountId: "5beee0966d17bc42501f1234",
name: "Company Name 1",
contactEmail: "email1@email.com",
contactName: "contact Name 1"
reason: "Warranties",
total: 1152,
lineItems: [
{
_id: "5beee0966d17bc42501f5086",
jobsiteAddress: "1234 Street Southwest Sunnyville, Wyoming 12345",
warrantyFee: 384
},
{
_id: "5bf43929e7179a56e21382bc",
jobsiteAddress: "1234 Street Southwest Sunnyville, Wyoming 12345",
warrantyFee: 384
},
{
_id: "5bf4392fe7179a56e21382bd",
jobsiteAddress: "1234 Street Southwest Sunnyville, Wyoming 12345",
warrantyFee: 384
}
]
},
{
_accountId: "5beee0966d17bc42501f1235",
name: "Company Name 2",
contactEmail: "email2@email.com",
contactName: "contact Name 2"
reason: "Warranties",
total: 1152, …Run Code Online (Sandbox Code Playgroud) mongoose mongodb mongodb-query aggregation-framework mongoose-populate
我试图用与其相关的教程填充标签,当我在查询上使用 .populate() 时,它可以工作,但是当我直接在模型上执行此操作时,我有一个无限循环。
这是我的代码:
标签.js
const mongoose = require("mongoose");
const tagSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
unique: true,
trim: true
}
},
{
toObject: { virtuals: true },
toJSON: { virtuals: true }
}
);
tagSchema.virtual("tutorials", {
ref: "Tutorial",
foreignField: "tags",
localField: "_id"
});
tagSchema.pre(/^find/, function(next) {
// That's the code that causes an infinite loop
this.populate({
path: "tutorials",
select: "-__v"
});
next();
});
const Tag = mongoose.model("Tag", tagSchema);
module.exports = Tag;
Run Code Online (Sandbox Code Playgroud)
教程.js
const mongoose …Run Code Online (Sandbox Code Playgroud) 我目前正在开发一个项目,其中虚拟填充是非常必要的:
有一个客户方案、一个文档方案以及一些其他引用客户的方案。在客户内部,我想填充引用的项目。
我已经有一个使用 Typegoose 的工作模型,由于后期不兼容,我不得不从项目中删除它。这是以前的工作方式:
@prop({
ref: () => DMSDocument,
foreignField: 'linkedCustomers', // compare this value to the local document populate is called on
localField: '_id', // compare this to the foreign document's value defined in "foreignField",
justOne: false
})
public documents: { type: Types.ObjectId, ref: 'DMSDocument' }[];
Run Code Online (Sandbox Code Playgroud)
现在我试图仅在删除 typegoose 后使用Nestjs/mongoose来实现此目的:
@Prop({
virtual: 'documents',
ref: 'DMSDocument',
foreignField: 'linkedCustomers',
localField: '_id',
})
public documents: DMSDocument[];
Run Code Online (Sandbox Code Playgroud)
虚拟吸气剂工作得很好,因为我只是使用
@Schema({ toJSON: { virtuals: true, getters: true }, toObject: { virtuals: true, …Run Code Online (Sandbox Code Playgroud) 我想返回所有聊天对话,其中登录用户 (user_id) 是参与者。
我想填充参与者只返回 profile.firstname (以后可能会有其他一些),然后我想过滤掉参与者,以便它不会带回参与者数组中的登录用户(user_id)。
chat.controller.js 索引
Chat.find({participants: user_id})
.populate('participants', {
select: 'profile.firstname',
where('_id').ne(user_id) // This need to change
})
.exec(function (err, chats) { });
Run Code Online (Sandbox Code Playgroud)
聊天模型.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let ChatSchema = new Schema({
participants: [{
type: Schema.Types.ObjectId, ref: 'User'
}],
messages: [{
type: Schema.Types.ObjectId, ref: 'Message'
}],
},
{
timestamps: {createdAt: 'created_at', updatedAt: 'updated_at'}
});
module.exports = mongoose.model('Chat', ChatSchema);
Run Code Online (Sandbox Code Playgroud) mongoose ×10
mongodb ×8
node.js ×6
javascript ×2
express ×1
nestjs ×1
schema ×1
subdocument ×1