Reputation: 392
I try to find refs I've stored in my db by sending an array of object to my API. In the array I send there are 4 objects. 2 of them are already stored, 2 of them are new.
Here is what is stored in my DB:
[
{
ref: 'xxx14-010-S',
colorWay: 'Black',
},
{
ref: 'xxx18-050-S',
colorWay: 'Black',
},
...
]
My req.body look like this :
[
{
ref: 'xxx14-010-S',
colorWay: 'Black',
},
{
ref: 'xxx18-050-S',
colorWay: 'Black',
},
{
ref: 'xxx20-010-S',
colorWay: 'Black',
},
{
ref: 'xx324-010-S',
colorWay: 'Black',
}
]
And here is the code in my express router:
router.post("/api/v1/lineList", async (req, res, next) => {
try {
const existingRefs = await LineList.find({ref: {$in: req.body.ref}});
res.send(existingRefs);
} catch (err) {
next(err);
}
});
This returns an empty array where I expect to find the 2 stored objects. How shall I proceed ? Is there a way to get the 2 found objects and also be notified that the 2 other object where not in the db ?
Thanks a lot !
EDIT: Here is the model:
const lineListSchema = new mongoose.Schema({
ref: {
type: String,
required: true,
unique: true,
trim: true,
uppercase: true,
},
styleName: {
type: String,
required: true,
trim: true,
uppercase: true,
},
colorWay: {
type: String,
required: true,
trim: true,
uppercase: true,
},
...
createdAt: {
type: Date,
default: Date.now,
expires: 3600,
},
});
Upvotes: 0
Views: 71
Reputation: 11975
$in syntax is:
{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }
So you need to pass an array like this:
await LineList.find({ ref: { $in: req.body.map(val => val.ref) } });
Upvotes: 1