标签: mongoose-populate

我怎样才能在mongoose中聚合和填充

我在填充"Main"集合时遇到了问题,分组工作得很好,但我真的不知道如何填充,甚至在聚合后找到.find.我相信我在这里做模特铸造:

Main.aggregate([
      {$match : query},
      {
        $group:{
          _id: queryGroupBy,
          activated: {$sum: '$activated'},
          componentTitle: {$first:'$componentTitle'},
          titlePrefix: {$first:'$titlePrefix'},
          operator_name: {$first:'$operator_name'}
        }
      },
      {
        $project:{
          _id: '$_id',
          summation: '$activated',
          componentTitle: '$componentTitle',
          titlePrefix: '$titlePrefix',
          operator_name: '$operator_name'   
        }
      }],
      function(err,results) {
        if (err) throw err;
        result = results.map(function(doc) { 
          doc._id = doc._id,
          doc.activated = doc.activated,
          doc.componentTitle = doc.componentTitle,
          doc.titlePrefix = doc.titlePrefix,
          doc.operator_name = doc.operator_name,
          doc.fssStatusFDD = "",
          doc.dateUpdated = "",
          delete doc._id;
          delete doc.summation;

            var _main = new Main();
            _main = doc;
            console.log('test3');
            return _main …
Run Code Online (Sandbox Code Playgroud)

aggregate mongoose mean-stack mongoose-populate

3
推荐指数
1
解决办法
5054
查看次数

猫鼬分布在2个数据库中

我有node app使用2数据库的。一个是the Names,另一个是其余的所有数据。

我有此连接设置:

// DATABASE CONNECTION
var APP_DB_URI = config.APP_DB; // mongodb://localhost:27017/app_db
var app_DB = mongoose.createConnection(APP_DB_URI);
var name_DB = app_DB.useDb(config.NAME_DB); // 'name_db'
Run Code Online (Sandbox Code Playgroud)

此连接工作正常。

将数据保存到两者app_dbnames_db完美工作也没有问题。

但是问题是这样的:当我尝试查询Account模型时,再填充所引用的Name模型,则填充过程返回null

帐户架构:

 var mongoose = require('mongoose');
 var Schema = mongoose.Schema;
 var field = {
     email: {type: String, unique: true},
     password: {type: String, select: false},
     name: {type: Schema.Types.ObjectId, ref: 'Name'},
 }

 var options = {
     id: false,
     versionKey: false
 }

 var schema …
Run Code Online (Sandbox Code Playgroud)

mongoose mongodb node.js mongoose-populate

3
推荐指数
1
解决办法
1963
查看次数

Mongoose深度填充多个第二级对象无法正常工作

我有一个模特A机智这个领域:

var field = {
    foo: String,
    b: [{ type: Schema.Types.ObjectId, ref: 'B' }]
}  
Run Code Online (Sandbox Code Playgroud)

B这个领域的模型:

var field = {
    c: { type: Schema.Types.ObjectId, ref: 'C' } // let's say this has 3 string field
    d: { type: Schema.Types.ObjectId, ref: 'D' } // so was this
}
Run Code Online (Sandbox Code Playgroud)

基于此答案郑氏晃新和成做这个-

 A.find({_id:req.params.id})
    .populate({ path: 'patient', model: Patient,
        populate: {
            path: 'b',
            model: B
        },
        populate: {
            path: 'c',
            model: C
        },
    })
    .exec(function (err, doc) …
Run Code Online (Sandbox Code Playgroud)

mongoose mongodb node.js mongoose-populate

3
推荐指数
1
解决办法
1557
查看次数

使用 Mongoose populate() 清理死引用

如果用户有一个名为“tags”的数组:

var User = new Schema({
    email: {
        type: String,
        unique: true,
        required: true
    },
    tags: [{
        type: mongoose.Schema.Types.ObjectId,
        ref:'Tag',
        required: true
    }],
    created: {
        type: Date,
        default: Date.now
    }
});
Run Code Online (Sandbox Code Playgroud)

我对查询执行 populate('tags') :

User.findById(req.params.id)
    .populate("tags")
    .exec(function(err, user) { ... });
Run Code Online (Sandbox Code Playgroud)

如果列表中的标签之一实际上已被删除,是否有办法删除“标签”中的这个死引用?

目前,返回的用户对象正在返回所需的结果——即。只有实际存在的标签才存在于标签数组中...但是,如果我查看 mongodb 中的底层文档,它仍然包含数组中的死标签 id。

理想情况下,我想懒惰地清理这些引用。有谁知道这样做的好策略?

mongoose mongodb mongoose-populate mongoose-schema

3
推荐指数
1
解决办法
2649
查看次数

MongoDB/Mongoose 一对多,参考孩子中的父母 - 分组并加入

我按照 Mongo 文档中的建议在子集合中参考父集合,因为子集合有增长的前景。 https://docs.mongodb.com/manual/tutorial/model-referenced-one-to-many-relationships-between-documents/

发布者(父)集合:

{
   _id: "oreilly",
   name: "O'Reilly Media",
   founded: 1980,
   location: "CA"
}
Run Code Online (Sandbox Code Playgroud)

图书(儿童)收藏 - 参考其中的出版商:

{
   _id: 123456789,
   title: "MongoDB: The Definitive Guide",
   author: [ "Kristina Chodorow", "Mike Dirolf" ],
   published_date: ISODate("2010-09-24"),
   pages: 216,
   language: "English",
   publisher_id: "oreilly"
},{
   _id: 234567890,
   title: "50 Tips and Tricks for MongoDB Developer",
   author: "Kristina Chodorow",
   published_date: ISODate("2011-05-06"),
   pages: 68,
   language: "English",
   publisher_id: "oreilly"
}
Run Code Online (Sandbox Code Playgroud)

现在我想要实现的是让所有出版商拥有他们的书籍子数组:

    {
  "_id": "oreilly",
  "name": "O'Reilly Media",
  "founded": 1980,
  "location": "CA",
  "books": [
    {
      "_id": …
Run Code Online (Sandbox Code Playgroud)

mongoose mongodb mongodb-query mongoose-populate

3
推荐指数
1
解决办法
604
查看次数

猫鼬如何从填充中排除_id

我正在我的角色文档中填充 _group

return this.find(query, {'_group': 1, 'name':1, 'description': 1} )
  .populate('_group', ['name', 'description'])
  .sort({ createdAt: -1 })
  ...
Run Code Online (Sandbox Code Playgroud)

我也得到了 _group 的 _id

{"_id":"5959ef7db9938a0600f05eb2",
"_group":{
    "_id":"5959ef7db9938a0600f05eae",
    "name":"GroupA",
     "description":"Description GroupA"
 },
"name":"manager",
"description":"can R group, can RW user"},
Run Code Online (Sandbox Code Playgroud)

我怎样才能摆脱 _group._id ?

我试过:

 return this.find(query, {'_group': 1, 'name':1, '_group._id':0, '_id':0} )
Run Code Online (Sandbox Code Playgroud)

但它引发了一个错误:投影不能混合包含和排除。

return this.find(query, {'_group': 1, 'name':1, '_id':0, '_id':0}
Run Code Online (Sandbox Code Playgroud)

仅删除角色._id

感谢反馈

mongoose node.js mongoose-populate

3
推荐指数
1
解决办法
2820
查看次数

使用Mongoose-paginate插件填充多个Mongoose模型字段

我有一个Mongoose Schema(约会),有两个reffield(发送者和接收者).两者都引用相同的Schema(用户).我试图使用mongoose-paginate插件填充这两个字段.

约会架构片段.

var paginate = require('mongoose-paginate');

var AppointmentSchema = new Schema({
  dateCreated: {type: Date, default: Date.now},
  sender: {type: ObjectId, ref: 'User'},
  receiver: {type: ObjectId, ref: 'User'},
  message: String,
  
  .........................
  
AppointmentSchema.plugin(paginate);

var Appointment = mongoose.model('Appointment', AppointmentSchema);
module.exports = Appointment;
Run Code Online (Sandbox Code Playgroud)

用户架构片段.

var UserSchema = new Schema({
  username: String,
  name: {
    first: String,
    middle: String,
    last: String
  },
  
  ..................
  
var User = mongoose.model('User', UserSchema);

module.exports = User;
Run Code Online (Sandbox Code Playgroud)

mongoose paginate查询.

Appointment.paginate({}, request.query.page, request.query.limit,
    function(error, pageCount, appointments, itemCount) {
      if (error) {
         return console.log('ERRRRRRRRRR'.red); …
Run Code Online (Sandbox Code Playgroud)

mongoose node.js express mongoose-populate

2
推荐指数
1
解决办法
4408
查看次数

猫鼬填充不适用于 ObjectIds 数组

这是我的架构:

/** Schemas */
var profile = Schema({
    EmailAddress: String,
    FirstName: String,
    LastName: String,
    BusinessName: String
});

var convSchema = Schema({
    name: String,
    users: [{
        type: Schema.Types.ObjectId,
        ref: 'Profiles'
    }],
    conversationType: {
        type: String,
        enum: ['single', 'group'],
        default: 'single'
    },
    created: {
        type: Date,
        default: Date.now
    },
    lastUpdated: {
        type: Date,
        default: Date.now
    }
});

/** Models */
db.Profiles = mongoose.model('Profiles', profile);
db.Conversations = mongoose.model('ChatConversations', convSchema);

module.exports = db;
Run Code Online (Sandbox Code Playgroud)

然后我尝试使用以下代码(http://mongoosejs.com/docs/populate.html)填充用户:

db.Conversations.find(query).populate('users').exec(function (err, records)     {
    console.log(records);
});
Run Code Online (Sandbox Code Playgroud)

这是返回records …

mongoose mongodb node.js mongoose-populate mongoose-schema

2
推荐指数
1
解决办法
3122
查看次数

猫鼬填充不填充数组

我已经在这个mongoose.model.populate功能上挣扎了几个小时了。我什至尝试过直接复制和粘贴几个解决方案而没有运气。

我有一个用户模型,它应该包含他/她创建的“困境”数组,但我无法填充它。

以下是模型以及populate().

用户.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

// Create Schema
const UserSchema = new Schema({
  username: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  },
  dilemmas: [
    {
      type: Schema.Types.ObjectId,
      ref: "Dilemma"
    }
  ]
});

module.exports = User = mongoose.model("User", UserSchema, "users");
Run Code Online (Sandbox Code Playgroud)

困境.js

const mongoose = require("mongoose");
const slug = require("mongoose-slug-generator");
const Schema …
Run Code Online (Sandbox Code Playgroud)

javascript mongoose mongodb nosql mongoose-populate

2
推荐指数
2
解决办法
1652
查看次数

猫鼬填充数组中的单个项目

我有一个包含动态引用数组的模型。

var postSchema = new Schema({
  name: String,
  targets: [{
    kind: String,
    item: { type: ObjectId, refPath: 'targets.kind' }
  }]
}); 
Run Code Online (Sandbox Code Playgroud)

我正在使用目标属性来存储对多个不同模型、用户、线程、附件等的引用。

是否可以只填充我想要的引用?

Post.find({}).populate({
  // Does not work
  // match: { 'targets.kind': 'Thread' }, // I want to populate only the references that match. ex: Thread, User, Attachment
  path: 'targets.item',
  model: 'targets.kind',
  select: '_id title',
});
Run Code Online (Sandbox Code Playgroud)

谢谢

mongoose mongodb mongoose-populate

2
推荐指数
1
解决办法
3028
查看次数