我有一个像这样的猫鼬模式:
const userSchema = new Schema( {
email:{ type: String, required: true, unique:true, index:true },
mobile:{ type: String },
phone:{ type: String },
firstname: { type: String },
lastname: { type: String },
profile_pic:{type:String},
socialHandles: {
type: Map,
of: String
},
active: {type:Boolean, default:true}
}, {
timestamps: true
} );
Run Code Online (Sandbox Code Playgroud)
我想查询“给我用户,socialHandles.instagram=jondoe”,我该怎么做?请帮忙
我正在尝试在in和的子字段中添加createdAt和updatedAt时间戳otpgenerate: {}verify:{}
我知道使用会将和时间戳{ timestamps: true }添加到整个架构中。createdAtupdatedAt
const userSchema = new mongoose.Schema({
email: { type: String, unique: true },
name: { type: String },
mobileNumber: {
isVerified: {type: Boolean, default: false},
otp: {
generate: {
attempts: {type: Number, default: 0},
total: {type: Number, default: 0},
createdAt: {type: Date},
updatedAt: {type: Date}
},
verify: {
attempts: {type: Number, default: 0},
total: {type: Number, default: 0},
createdAt: {type: Date},
updatedAt: {type: Date} …Run Code Online (Sandbox Code Playgroud) 我想知道用户/通知类型场景的最佳方案是什么,如下所示:
1 | 01-04-2020 | X | John liked your post2
2 | 01-03-2020 | X | Mike and 9 other persons liked your post1
3 | 01-02-2020 | | Rose and 2 other persons liked your post1
4 | 01-01-2020 | | Bernard liked your post1
x = notification has not been read by the user yet
post1 = the same post in all the notifications
Run Code Online (Sandbox Code Playgroud)
假设我有一个通知集合,例如:
_id: ObjectID
receiver: ObjectID (User)
sender : ObjectID (User)
type: String ("post", …Run Code Online (Sandbox Code Playgroud) 在下面的代码中,注释的电子邮件架构是以前的,我不再希望电子邮件是必需的,并且是唯一的,它应该是可选的。
我收到一条错误,说重复,为空“E11000重复键错误集合:mydb.lists索引:email_1 dup键:(电子邮件:null)”
const mongoose = require("mongoose");
const { Schema } = mongoose;
const alliedSchema = new Schema(
{
name: String,
phone: String,
email: {
unique: false,
type: String
},
// email:{
// type: String,
// unique: true,
// required: true,
// lowercase: true,
// validate(value){
// if(!validator.isEmail(value)){
// throw new Error('Email is invalid')
// }
// }
// },
picture: {
type: String,
default: "https://www.dialadocdirect.org/app/storage/images/noimage.jpg",
},
location: String,
type: String,
verified: {
type: Boolean,
default: false,
},
},
{ …Run Code Online (Sandbox Code Playgroud) 在我的应用程序中,我有一个帖子架构(如下所示):
const postSchema = new mongoose.Schema({
file: {
type: String,
required: true
},
caption: {
type: String,
maxLength: 2000
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
likeNum: {
type: Number,
default: 0,
min: 0
},
likes: [{
type: mongoose.Schema.Types.ObjectId
}]
})
Run Code Online (Sandbox Code Playgroud)
objectid我想在发送用户请求时从 Like 数组中删除 an 。
路线:
const post = await Post.findOne({_id: req.params.postid})
const user = req.user._id
post.update({}, {$pull: {likes: user}})
post.likeNum--
await post.save()
res.send('Unliked')
Run Code Online (Sandbox Code Playgroud)
然而,objectid当调用路由时, 不会从数组中删除。有人能看出为什么吗?谢谢。
更新:
const user = mongoose.Types.ObjectId(req.user._id)
Run Code Online (Sandbox Code Playgroud)
更新2:
Post.updateOne({_id: req.params.postid}, { …Run Code Online (Sandbox Code Playgroud) 根据文档,我有以下架构:
const toolRecordSchema = new mongoose.Schema({
userId: { type: mongoose.Schema.Types.ObjectId },
});
toolRecordSchema.virtual("user", {
ref: "User",
localField: "userId",
foreignField: "_id",
justOne: true,
})
Run Code Online (Sandbox Code Playgroud)
当我填充虚拟时,什么也没有发生:
db.ToolRecord.find().populate("user")
Run Code Online (Sandbox Code Playgroud)
但是,如果我将“ref”添加到userId模式中,然后执行.populate("userId"),它会按预期工作,这意味着问题不在于模型之间的关系,而在于虚拟群体。
有什么想法我做错了什么吗?
如果我添加mongoose.set("debug", true),我可以看到将.populate("user")查询产品添加到猫鼬调试日志中的输出:
users.find({}, { skip: undefined, limit: undefined, perDocumentLimit: undefined, projection: {}})
Run Code Online (Sandbox Code Playgroud)
并添加.populate("userId")(有效的)产品此日志:
users.find({ _id: { '$in': [ new ObjectId("631a1fe960d1f82c7fa51a06") ], [Symbol(mongoose#trustedSymbol)]: true }}, { skip: undefined, limit: undefined, perDocumentLimit: undefined, projection: {}})
Run Code Online (Sandbox Code Playgroud)
这样我们就可以看到问题出在哪里。问题是为什么虚拟人口不起作用?
我正在运行猫鼬6
我是 nodejs 的新手。我有一个带有 mongoose 和用户登录的应用程序。mongoDB 中的一些集合是针对所有用户的,而另一些则例如 customer-collection 是单独的,因此所有用户都有自己的客户集合。当用户登录并获取他的 jwt-token 时,各个猫鼬模型将被实例化:
var models = require('../models')(userID);
Run Code Online (Sandbox Code Playgroud)
在文件夹 /models 中有一个 index.js:
var Customer = require('./customermodel');
module.exports = function (userID) {
Customer(userID)
}
Run Code Online (Sandbox Code Playgroud)
文件/models/customermodel.js:
var mongooseCustomer = function(userID) {
var schema = mongoose.Schema({
_id: { type: Number},
Name: { type: String },
Address: { type: String },
}, {collection: userID + 'userID'})
return mongoose.model(userID + 'customer', schema);
}
Module.exports = mongooseCustomer;
Run Code Online (Sandbox Code Playgroud)
当客户从两个不同的浏览器登录并返回错误时会出现问题:无法覆盖123customer模型一旦编译。我通过改变解决了这个问题:
var models = require('../models')(userID);
Run Code Online (Sandbox Code Playgroud)
到:
try {
var models = …Run Code Online (Sandbox Code Playgroud) 我正在尝试在数据库上运行mongoose.findOne,但是得到了意外的结果。我的查询是
const User = mongoose.model('User', {name: String, email: String, passwordHash: String, validation: String, validationCode: String, favorites: Array })
exports.findUser = function findUser(email){
const foundUser = User.findOne({email: email}, function(err, userObj){
if(err){
return err
} else if (userObj){
return userObj
} else{
return null
}
})
return foundUser
}
Run Code Online (Sandbox Code Playgroud)
但是,这将返回以下数据(看似随机?),并且没有我请求的任何数据
Query {
_mongooseOptions: {},
mongooseCollection:
NativeCollection {
collection: null,
opts: { bufferCommands: true, capped: false },
name: 'users',
collectionName: 'users',
conn:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: …Run Code Online (Sandbox Code Playgroud) 我有一个这样保存在MongoDB中的文档:
{
title: 'title',
author: 'author name',
body: 'the body',
admin: 'admin user'
}
Run Code Online (Sandbox Code Playgroud)
这是猫鼬的模式:
var blogSchema = new Schema({
title: String,
author: String,
body: String
});
Run Code Online (Sandbox Code Playgroud)
我想保存后,就从文档中删除了“ admin”字段,这可能吗?我可以在事件预保存时自动执行此操作吗?
谢谢。
我想创建每个都有各自独特的访问“代码”的“游戏”。代码required在模式中,每次创建新游戏时,我都需要生成一个代码。
我认为schema.pre('init')这是生成此访问代码的好地方:
GameSchema.pre('init', function(next) {
// Code generation logic happens here
this.code = myNewlyGeneratedCode
next()
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,这返回一条错误消息: ValidationError: Game validation failed: code: Path 'code' is required.
为什么不起作用?我必须code在实例化新游戏之前创建一个吗?