[英]How to define a new field in a pre-existing document in MongoDB that isn't in the schema? (Node.js)
I am making a discord bot using MongoDB and I want to add some user-specific fields to an already existing document in MongoDB that aren't in the schema. 我正在使用MongoDB做一个不和谐的机器人,我想将一些特定于用户的字段添加到不在模式中的MongoDB中已经存在的文档中。 There is a lot of data I am planning to add and I wanted it to be added automatically depending on what the user does for efficiency.
我打算添加很多数据,我希望根据用户为提高效率而自动添加数据。
I tried to use findOneAndUpdate to set the new field and its value. 我试图使用findOneAndUpdate设置新字段及其值。 I had the settings "strict" set to false and "upsert" set to true.
我将设置“ strict”设置为false,将“ upsert”设置为true。 I saved it afterwards.
我后来保存了。 I did see that it was added in the Compass Community App, but when I tried to call the field later, it was undefined and I'm assuming because it isn't in the schema.
我确实看到它是在Compass社区应用程序中添加的,但是当我稍后尝试调用该字段时,它是未定义的,我假设是因为它不在架构中。 I wanted to know if there was a way around this or if I made any errors.
我想知道是否可以解决此问题,或者是否出错。
Users.findOneAndUpdate({
userID: message.author.id
}, {
$set: {
"xp": xpToBeAdded,
"level": 0
}
}, {
strict: false,
upsert: true
}, async (err, userAdd) => {
await userAdd.save().catch(err => console.log(err))
})
Original users schema: 原始用户架构:
const mongoose = require("mongoose");
const userSchema = mongoose.Schema({
userID: String,
serverID: Array,
userTag: String,
username: String,
dbCreatedAt: Number,
dbCreatedAtDate: String
}, {strict: false})
module.exports = mongoose.model("User", userSchema)
If you are seeing the right values in compass, but it's not being returned, it's probably because your model doesn't know about those properties. 如果您在罗盘中看到了正确的值,但没有返回,则可能是因为您的模型不知道这些属性。 Try updating your model to this:
尝试将模型更新为此:
const mongoose = require("mongoose");
const userSchema = mongoose.Schema({
userID: String,
xp: Number,
level: Number,
serverID: Array,
userTag: String,
username: String,
dbCreatedAt: Number,
dbCreatedAtDate: String
}, {strict: false})
module.exports = mongoose.model("User", userSchema)
Example of what is happening (notice how sex
doesn't get logged, even though you're passing it in as a value): 发生的情况的示例(注意,即使您将性作为值传递,也不会记录
sex
):
class User { constructor(user) { this.name = user.name; this.age = user.age; } } const user1 = new User({name: 'Frank', age: 22, sex: 'M'}); console.log(user1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.