Mongoose: how to define a combination of fields to be unique?
You can define a unique compound index using an index call on your schema: person.index({ firstName: 1, lastName: 1}, { unique: true });
You can define a unique compound index using an index call on your schema: person.index({ firstName: 1, lastName: 1}, { unique: true });
A couple tips: Try running the same query from mongodb at the command line, see if you get any results. Is the “campaign_id” defined as an ObjectId in your schema? If so, try searching using the ObjectId type. For example: var ObjectId = require(‘mongoose’).Types.ObjectId; var query = { campaign_id: new ObjectId(campaign._id) };
Update: Starting from v4.4 there is a dedicated operator $first: { $project: { user: { $first: “$users” }, otherField: 1 }}, It’s a syntax sugar to the Original answer: You can use arrayElemAt: { $project: { user: { $arrayElemAt: [ “$users”, 0 ] }, otherField: 1 }},
Use query.select for field selection in the current (3.x) Mongoose builds. Prefix a field name you want to exclude with a -; so in your case: Query.select(‘-Image’); Quick aside: in JavaScript, variables starting with a capital letter should be reserved for constructor functions. So consider renaming Query as query in your code.
statics are the methods defined on the Model. methods are defined on the document (instance). You might use a static method like Animal.findByName: const fido = await Animal.findByName(‘fido’); // fido => { name: ‘fido’, type: ‘dog’ } And you might use an instance method like fido.findSimilarTypes: const dogs = await fido.findSimilarTypes(); // dogs => [ … Read more
On express 3 you can use directly res.json({foo:bar}) res.json({ msgId: msg.fileName }) See the documentation
MongoError: ns not found occurs when performing actions on collections that don’t exist. For example, attempting to drop indexes before an explicit collection creation has occurred or before adding a document to the collection which implicitly creates the collection.
Just to give an update for Mongoose 3.x: MyModel.find().distinct(‘_id’, function(error, ids) { // ids is an array of all ObjectIds });
I had the same problem, and in my case, the answer was as simple as removing the angle brackets “<“and “>” around <password>. I had been trying: my_login_id:<my_password>, when it should have been my_login_id:my_password.
I suggest you to use 2 queries: db.collection.count() will return total number of items. This value is stored somewhere in Mongo and it is not calculated. db.collection.find().skip(20).limit(10) here I assume you could use a sort by some field, so do not forget to add an index on this field. This query will be fast too. … Read more