0

I'm trying to get document that it's 'from' field value in 'from' of 'periods' array.

I've tried followings but it doesn't work. how can i?

periods = [{
    from: 333,
    to: 555
},
{
    from: 666,
    to: 777
}]

var eqbookschema = new Schema({
eq_dbId: String,
user_dbId: String,
from: Number,
to: Number,
timestamp: Number,
}, {collection: 'book'});

EQBook = mongoose.model('EQBook', eqbookschema)

EQBook.find({
    eq_dbId: req.body.eq_dbId,
    from: {$in: [periods.from]}
})

The query I have tried only returns empty array although existing.

3 Answers 3

1

Because periods is an array of object and you want to find based on from field of each element so you need to map it first:

let froms = periods.map(val => val.from);

Then find with mapped array:

EQBook.find({
  eq_dbId: req.body.eq_dbId,
  from: {$in: froms}
})

Or just:

EQBook.find({
  eq_dbId: req.body.eq_dbId,
  from: {$in: periods.map(val => val.from)}
})
Sign up to request clarification or add additional context in comments.

6 Comments

is there no other way using mongoose query?
What do you mean? It's using mongoose query, just edit the input to filter result.
using that way, periods not changed?
Yes, .map() doesn't modify the orginal array.
is there no other way using mongoose operator?
|
0

create an array of 'from' values only

periodFrom = periods.map((elem)=>elem.from);

EQBook.find(
  {eq_dbId: req.body.eq_dbId,from:{$in:periodFrom}}
)

2 Comments

as you can see in in the model, EQBook has no 'periods' field.
thank you for your help. you' right, but i can only one accept. sorry.
0

You can try this.

const ObjectId = require('mongodb').ObjectId;
let froms = periods.map(data => data.from);
EQBook.aggregate([
{
 $match : {'eq_dbId': ObjectId(req.body.eq_dbId),'from':{$in:[periodFrom]}
}
])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.