These are chat archives for Automattic/mongoose

11th
Oct 2018
miguelangeljaimen
@miguelangeljaimen
Oct 11 2018 01:58
hello, good nigth
i need transform a mongodb query in mongoose function
the mongodb query is "db.propiedads.find({_id:ObjectId("5bb18cc42a8f2d23d8dfcd65"),"planes.plan":ObjectId("5bb565f6382cf30364b182e5")})"
Kev
@lineus
Oct 11 2018 02:28
@miguelangeljaimen mongoose will cast the string representations of those objectIds for you as long as the schema paths are defined as objectIds. The mongoose shorthand for this query would be Model.find({ _id: '5bb18cc42a8f2d23d8dfcd65' }, 'planes.plan': '5bb565f6382cf30364b182e5' });
as long as you've defined your schema with the default _id path, or explicitly with _id: mongoose.Schema.Types.ObjectId, and your planes path looks something like:
planes: { 
  plan: { 
    type: mongoose.Schema.Types.ObjectId 
    } 
  } 
}
miguelangeljaimen
@miguelangeljaimen
Oct 11 2018 02:46
I understand, in fact my model is that way, my problem is that before adding a new plan, I need to validate if that plan already exists in the property, that is the idea of the query.

'use strict'

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var tipos = ['CASA','DEPARTAMENTO','EMPRESA','CONDOMINIO'];

var PropertySchema = Schema({
tipo:{
type:String,
enum:{values:tipos, message:'Tipo de propiedad no valida'}
},
direccion: {
comuna: {
type:String,
required:true
},
calle:{
type:String,
required:true
},
numero:{
type:Number,
required:true
},
departamento: String},
id_usuario:{
type: Schema.ObjectId,
ref:'Usuario',
required:true
},
fecha_inscripcion:Date,
fecha_actualización:Date,
planes:[
{
plan:{
type: Schema.ObjectId,
ref:'Plan',
_id : false
},
create:Date
}],
});

module.exports = mongoose.model('Propiedad' ,PropertySchema);

@lineus this is my model
Kev
@lineus
Oct 11 2018 10:11
@miguelangeljaimen because planes is an array, you can use the $addToSet operator to only add unique values to the array. here's an example gist
note that, by default, mongoose adds an _id property to array elements, I've disabled them in my schema to take advantage of $addToSet.