想象一下,我有以下型号:
# MODEL A
schemaA = mongoose.Schema
_bId:
type: mongoose.Schema.Types.ObjectId
ref: "B"
# MODEL B
schemaB = mongoose.Schema
_cId:
type: mongoose.Schema.Types.ObjectId
ref: "C"
_dId:
type: mongoose.Schema.Types.ObjectId
ref: "D"
# MODEL C
schemaC = mongoose.Schema
_eId:
type: mongoose.Schema.Types.ObjectId
ref: "E"
Run Code Online (Sandbox Code Playgroud)
模型D和E没有任何其他对象引用,因此不再列出为方便起见.
使用所有引用填充模型"A"的最佳实践是什么?目前我按如下方式解决此任务(它是一个实例方法,因为我经常需要它):
schemaA.methods =
populateAll: (cb) ->
@
.populate
path: "_bId"
model: "B"
populate:
path: "_cId"
model: "C"
populate:
path: "_eId"
model: "E"
, (error) =>
return cb error, @ if error?
D.findById @._bId._dId
.exec (error, d) =>
return cb error, …Run Code Online (Sandbox Code Playgroud) 我希望location默认情况下隐藏我的架构的字段.我添加了select: false属性,但在选择文档时总是返回...
var userSchema = new mongoose.Schema({
cellphone: {
type: String,
required: true,
unique: true,
},
location: {
'type': {
type: String,
required: true,
enum: ['Point', 'LineString', 'Polygon'],
default: 'Point'
},
coordinates: [Number],
select: false, <-- here
},
});
userSchema.index({location: '2dsphere'});
Run Code Online (Sandbox Code Playgroud)
致电时:
User.find({ }, function(err, result){
console.log(result[0]);
});
输出是:
{
cellphone: '+33656565656',
location: { type: 'Point', coordinates: [Object] } <-- Shouldn't
}
Run Code Online (Sandbox Code Playgroud)
编辑: 解释(感谢@alexmac)
SchemaType select选项必须应用于字段选项而不是类型.在您的示例中,您已定义了复杂类型的Location,并为类型添加了select选项.
考虑一个非常简单的Express 4应用程序结构:
-- app.js
-- models
|--db.js
|--news.js
Run Code Online (Sandbox Code Playgroud)
其中news.js包含猫鼬模式和基于该模式的模型:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var newsSchema = new Schema({
title: String,
subtitle: String,
// other fields...
});
var News = mongoose.model('News', newsSchema);
Run Code Online (Sandbox Code Playgroud)
据我了解,为了app.js使用News模式,它有权要求这样的脚本中的文件:require('./models/news')。此外,news.js还必须像这样导出模型:module.exports = News;。
但是,我遇到了许多脚本,它们不会导出在单独文件中定义的模型(或任何与此相关的内容),而仅通过要求模型文件和然后做这样的事情:
var mongoose = require('mongoose');
var News = mongoose.model('News');
Run Code Online (Sandbox Code Playgroud)
这怎么可能?这是猫鼬的特色吗?如果未在另一个文件中导出模型/模式,文件如何使用该文件中定义的模型或架构?
我想知道是否有一种方法让用户使用用户名或电子邮件登录 我搜索了很多次但没有找到工作方法.我不知道如何做到这一点,请尽可能以最简单的方式帮助.这是我的用户架构的样子:
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new mongoose.Schema({
fullname: String,
username: { type : String , lowercase : true , unique: true , required: true, minlength: 3, maxlength: 10},
email: String,
password: String,
mobile: String,
gender: String,
profession: String,
city: String,
country: String,
joining: {type: Date, default: Date.now}
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
Run Code Online (Sandbox Code Playgroud)
添加信息:我正在使用nodejs.任何帮助都非常感谢.日Thnx
编辑
最小的复制回购
在代码中解释比在英语中更容易.下面的代码可以工作,但感觉就像是一个更简单,更MongoDBy/mongoosy方式...
// recipeModel.js, relevant part of the schema
equipments: [{
_id: {
type: Schema.Types.ObjectId,
ref: 'equipments',
},
quantity: {
type: Number,
required: true,
},
}],
// recipeController.js
const equipmentsWorkaround = recipe => Object.assign({}, recipe.toObject(), {
equipments: recipe.toObject().equipments.map(equip => ({
quantity: equip.quantity,
name: equip._id.name,
_id: equip._id._id,
})),
})
const getItem = (req, res, next) => {
Recipes.findById(req.params.id)
.populate('equipments._id')
.then(equipmentsWorkaround) // <--- ugh ...
.then(recipe => res.json(recipe))
.catch(next)
}
Run Code Online (Sandbox Code Playgroud)
我知道如何ref在猫鼬中做一个"常规" ,但是我在这里甚至可能在mongo中吗?
期望的结果:
equipments: [
{
quantity: 1,
name: …Run Code Online (Sandbox Code Playgroud) mongoose express mongodb-query mongoose-populate mongoose-schema
我创建了一个Mongoose Schema并为Model添加了一些名为Campaign的静态方法.
如果我是console.log Campaign我可以看到它上面的方法.问题是我不知道在哪里添加这些方法,以便Typescript也知道它们.
如果我将它们添加到我的CampaignModelInterface,它们仅适用于模型的实例(或者至少TS认为它们是).
campaignSchema.ts
export interface CampaignModelInterface extends CampaignInterface, Document {
// will only show on model instance
}
export const CampaignSchema = new Schema({
title: { type: String, required: true },
titleId: { type: String, required: true }
...etc
)}
CampaignSchema.statics.getLiveCampaigns = Promise.method(function (){
const now: Date = new Date()
return this.find({
$and: [{startDate: {$lte: now} }, {endDate: {$gte: now} }]
}).exec()
})
const Campaign = mongoose.model<CampaignModelInterface>('Campaign', CampaignSchema)
export default Campaign
Run Code Online (Sandbox Code Playgroud)
我也试过通过Campaign.schema.statics访问它,但没有运气.
任何人都可以建议如何让TS了解模型中存在的方法,而不是模型实例?
假设我有3个node.js项目(1个应用后端,1个应用管理员后端,1个分析api)。在每个项目中,我都有一个模型架构调用贷款。
{
attributes: {
userId: { type: String, required: true, index: true, ref: 'users', comment: '??id' },
amount: { type: Number, required: true, min: 0},
totalAmount: { type: Number, required: true, min: 0},
penaltyInterest: { type: Number, min: 0, required: true, default:
0 }
}
methods: {
getFee () {//some calculation ops
}
save() {//some db ops
}
sendTo3rdComponent() {//some network ops
}
}
Run Code Online (Sandbox Code Playgroud)
该模型具有:一些方法,它是模式设计,api实现。如何在其他两个项目中重复使用它。
对于多个项目重用设计和api是非常重要的。
通常,我们通过将其作为npm包公开来重用该组件。但是,此组件具有自己的数据库操作和网络操作。是否可以将其作为npm软件包?
另一种选择是像eggjs
那么,复制粘贴旁边的优雅解决方案是什么?
该语法直接来自关于子类型的猫鼬文档。但是,我也看到了对子文档的替代引用。有什么不同?
https://mongoosejs.com/docs/subdocs.html
var childSchema = new Schema({ name: 'string' });
var parentSchema = new Schema({
// Array of subdocuments
children: [childSchema],
// Single nested subdocuments. Caveat: single nested subdocs only work
// in mongoose >= 4.2.0
child: childSchema
});
Run Code Online (Sandbox Code Playgroud)
对子文档的另一种引用类型
var childSchema = new Schema({ name: 'string' });
mongoose.model('children', childSchema);
var parentSchema = new Schema({
children: {
type: Schema.Types.ObjectId,
ref: 'children'
},
});
Run Code Online (Sandbox Code Playgroud) 我有一个情况,我正在检查文档是否已存在,如果不存在,我将创建一个新文档。我需要填充文档内的 2 个字段。我的问题是.create方法不支持.populate方法,因为如果我尝试这样做,我会收到错误。此外,. populate方法也不适用于返回的文档。如何正确填充新创建的文档?这是我的代码:
Favorite.create({ user: req.user._id, dishes: req.params.dishId })
.then((favorite) => {
favorite.populate('user');
favorite.populate('dishes');
console.log('Favorite marked', favorite);
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(favorite);
}, (err) => next(err))
}
})
.catch((err) => next(err));
Run Code Online (Sandbox Code Playgroud) 我有一个模型:
const comment = new mongoose.Schema({
id: { type: ObjectId, required: true },
comment: { type: String },
replies: [comment]
});
Run Code Online (Sandbox Code Playgroud)
想要创建这样的文档:
{
"id": 1,
"comment": "Grand Parent Comment",
"replies": [
{
"id": 11,
"comment": "Parent Comment",
"replies": [
{
"id": 111,
"comment": "Comment",
"replies": [
{
"id": 1111,
"comment": "Child Comment",
"replies": []
}
]
},
{
"id": 112,
"comment": "Sibling Comment",
"replies": []
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
根据这个答案的回答
this只需作为模型的参考即可解决。
{
"id": 1,
"comment": "Grand Parent …Run Code Online (Sandbox Code Playgroud)