mongoose关系devise

我最近开始在一个Node.js应用程序中使用Mongoose和Express.js,我有一个正确的方式来devise我的模式的问题。

我有几个有一些关系的模式,即位置模式有一个对象数组(它不是在这个上下文中的JS对象),而对象模式有它的位置属性。 我已经知道Mongoose中的关系是通过使用人口来解决的,但是当我实现这个方法的时候,我注意到我必须input很多重复的代码,也就是每当我想创build一个新的对象的时候,我也必须更新Location的数组对象,然后将该位置分配给该对象的属性。 在一个单独的查询中手动组装所有具有与我想从数据库中获取的位置相同的locationId属性的对象是不是更加简单?

我也考虑过将对象存储在位置文档的数组中(作为子文档),但是我决定要能够独立于位置(不查询位置)使用对象(创build,移除,更新),所以这种方法我猜不符合我的需求。 但是,在我的情况下,群体也有其缺点,所以我想这是最好的方式去手动收集由该位置的ID单独查询中的特定位置的对象。

我想听到这个技术的一些专业或高级用户对deviseMo​​ngoose模式的意见,以便我和其他人不会在后来保持和扩展我们的应用程序时遇到麻烦。

以下是我目前的模式:

var locationSchema = new mongoose.Schema({ title: String, objects: [{ type: String, ref: 'object' }] }); var objectSchema = new mongoose.Schema({ title: String, location: { type: String, ref: 'location' } }); 

结帐这个例子

DB / schemas.js:

 const Schema = mongoose.Schema; const ObjectSchema = { title: Schema.Types.String } const LocationSchema = new Schema({ title: Schema.Types.String, objects: [{type: Schema.Types.ObjectId, ref: 'Object'}] }) module.exports = { Object: ObjectSchema, Location: LocationSchema }; 

DB / model.js:

 const mongoose = require('mongoose'), schemas = require('./schemas'); module.exports = model => mongoose.model(model, schemas[model+'Schema']); 

用法:

 const model = require('./db/model'), LocationModel = model('Location'); LocationModel .findOne({_id: 'some id here'}) .populate('objects') .exec((err, LocationInstance) => { console.log(LocationInstance.title, ' objects:', LocationInstance.objects); }); 

当你创build一个对象并且想要关联到位置时:

 const model = require('./db/model'), ObjectModel = model('Object'), LocationModel = model('Location'); let ObjectInstance = new ObjectModel({title: 'Something'}); ObjectInstance.save((err, result) => { LocationModel .findByIdAndUpdate( 'some id here', {$push: {objects: ObjectInstance._id}}, (err) => { console.log('Object:', ObjectInstance.title, ' added to location'); }); }); 

更新对象数据:

  const model = require('./db/model'), ObjectModel = model('Object'); let id = 'id of object'; ObjectModel .findByIdAndUpdate( id, {title: 'Something #2'}, (err) => { console.log('Object title updated'); }); 

按对象查找位置:

  const model = require('./db/model'), LocationModel = model('Object'); let id = 'id of object'; LocationModel .findOne({objects: id}) .populate('objects') .exec((err, LocationInstance) => { console.log('Location objects:', LocationInstance.objects); }); 

没有什么特别的findOne({objects: id})会在对象数组中search与id有关系的位置文档

任何其他问题欢迎(: