gpt4 book ai didi

javascript - Mongoose 填充条件

转载 作者:行者123 更新时间:2023-11-30 09:59:29 25 4
gpt4 key购买 nike

Node.js 应用程序中使用 Mongoose(Mongodb),使用这段代码我获取用户和他们的书:

Users.find({user_id: req.user.id}).populate('books').exec(..);

现在我想获取拥有一本特殊书籍的用户。我喜欢这样:

Users.find({user_id: req.user.id}).populate('books',null,{bookname:"harry potter"}).exec(..);

但它不起作用。有了这个,我的代码获取用户的 null 值的书籍,如果该条件匹配,则返回它们而不是 null。事实上,我的大多数用户都对书籍有 null 值(value)。但我想要的是,如果填充部分中的条件不匹配,则根本不要在结果数组中返回该用户!

我必须做什么?我必须针对我需要的结果执行其他查询或其他操作吗?

最佳答案

我能想到的就是你说错了。除了您的 .populate() 参数看起来不正确之外,您在这里并没有真正显示太多上下文。

这是一个作为可重现示例的正确列表:

var async = require('async'),
mongoose = require('mongoose'),
Schema = mongoose.Schema;

var thingSchema = new Schema({
_id: Number,
name: String
},{ _id: false });

var parentSchema = new Schema({
name: String,
things: [{ type: Number, ref: 'Thing' }]
});

var Thing = mongoose.model( 'Thing', thingSchema ),
Parent = mongoose.model( 'Parent', parentSchema );

mongoose.connect('mongodb://localhost/thingtest');

var things = { "one": 1, "two": 2, "three": 3 };

async.series(
[
function(callback) {
async.each([Thing,Parent],function(model,callback) {
model.remove({},callback);
},callback);
},
function(callback) {
var parentObj = new Parent({ "name": "me" });
async.each(
Object.keys(things).map(function(key) {
return { "name": key, "_id": things[key] }
}),
function(thing,callback) {
var mything = new Thing(thing);
parentObj.things.push(thing._id)
mything.save(callback)
},
function(err) {
if (err) callback(err);
parentObj.save(callback);
}
);
},
function(callback) {
console.log("filtered");
var options = {
path: 'things',
match: { "name": { "$in": ['two','three'] } }
};

Parent.find().populate(options).exec(function(err,docs) {
if (err) callback(err);
console.log(docs);
callback();
});
},
function(callback) {
console.log('unfiltered');
Parent.find().populate('things').exec(function(err,docs) {
if (err) callback(err);
console.log(docs);
callback();
})
}
],
function(err) {
if (err) throw err;
mongoose.disconnect();
}
);

这将始终如一地给出这样的结果:

filtered
[ { _id: 55ec4c79f30f550939227dfb,
name: 'me',
__v: 0,
things:
[ { _id: 2, name: 'two', __v: 0 },
{ _id: 3, name: 'three', __v: 0 } ] } ]
unfiltered
[ { _id: 55ec4c79f30f550939227dfb,
name: 'me',
__v: 0,
things:
[ { _id: 1, name: 'one', __v: 0 },
{ _id: 2, name: 'two', __v: 0 },
{ _id: 3, name: 'three', __v: 0 } ] } ]

因此,请仔细查看您的数据和通话。 .populate() 调用需要匹配“路径”,然后还提供“匹配项”以查询要填充的文档。

关于javascript - Mongoose 填充条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32424230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com