我在填充"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) 我有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_db并names_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) 我有一个模特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) 如果用户有一个名为“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。
理想情况下,我想懒惰地清理这些引用。有谁知道这样做的好策略?
我按照 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) 我正在我的角色文档中填充 _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 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)这是我的架构:
/** 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.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) 我有一个包含动态引用数组的模型。
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 ×10
mongodb ×7
node.js ×5
aggregate ×1
express ×1
javascript ×1
mean-stack ×1
nosql ×1