node.js - mongoose query for an array of dictionaries -
how work arrays contain dictionaries? i'm trying post
fields can search text.
my attempts keep going using mongo
shell.
user.blog().find({}).where('post').in(writing).exec(function (err, result) { //do results }); // doesn't work
schema (edit: fixed @jam comments)
var blogschema = new mongoose.schema({ group: string, writing: [{ post: string, name : number }] }); var blog = mongoose.model('blog', blogschema);
update: adding json data , command put data in mongodb using mongo shell:
{ group: "design writing", writing: [{ post: "a very short post.", name: 10 }, { post: "an morning post everything.", name: 11 }] }
*or, here 1 line insert db in collection named my_collection
: *
db.my_collection.insert( {group: "design writing", writing: [{post: "a very short post.",name: 10}, {post: "an morning post everything.",name: 11}]} )
objects in writing
array treated sub/embedded-documents. means assigned _id
when stored in database.
so, there few ways can query blog
s based on these sub documents:
var objectid = mongoose.types.objectid; // assuming these objects in 'writing' array of blog var postobject = { post: 'some text', name: 10 }, postobjectwithid = { _id: new objectid(), post: 'some text', name: 10 }; // example #1 works! blog.find({'writing.post': postobject.post}) .exec(function(err, res){ onblogresult("ex#1", err, res) }); // example #2 works! blog.find({}) .where('writing').in([postobjectwithid]) .exec(function(err, res){ onblogresult("ex#2", err, res) }); // example #3 works - same example #2! blog.find({'writing': { $in: [ postobjectwithid ]}}) .exec(function(err, res){ onblogresult("ex#3", err, res) }); // example #4 fails because of missing _id on postobject! blog.find({'writing': { $in: [ postobject ]}}) .exec(function(err, res){ onblogresult("ex#4", err, res) });
as see, can find
objects array containing element using in
if have full object (including _id
).
you can view whole source on gist - test out :)
hope helps :)
Comments
Post a Comment