无法在MongoDB猫鼬文档中附加数组

问题描述

我正在尝试在mongo数据库添加一个空数组,并在前端(网站ui)中创建一个String,相关代码段如下:

猫鼬模式

server:
  port: 8080
  servlet:
    context-path: /tsp

使用passport和Google-oauth20创建文档

    email: String,displayName: String,googleId: String,toIgnore: [{toIgnoreURL: String}]
})

最后尝试添加用户”集合(当前登录用户的)的toIgnore数组属性

User.findOne({email: email.emails[0].value}).then((currentUser)=>{
            if(currentUser){
                // user does already exist
                console.log('welcome back!',currentUser)
                done(null,currentUser)
            }
            else{ // user doesn't exist yet
            new User({
                email: email.emails[0].value,displayName: email.displayName,googleId: email.id,toIgnore: []
            }).save().then((newUser)=>{
                console.log('new user created: ' + newUser)
                done(null,newUser)
            });
            }
        })

在mongodb中,我看到以下文档已成功创建

User.update(
        {email: emailThisSession},{$push: {toIgnore: {toIgnoreURL: url}}})

(也如所附图片所示) document in mongodb ui

我似乎不知道如何实际填充'toIgnore'数组。 例如,在控制台记录以下内容

_id
:ObjectId(
IdOfDocumentInMongoDB)
toIgnore
:
Array
email
:
"myactualtestemail"
googleId
:
"longgoogleidonlynumbers"
__v
:
0

输出var ignoreList = User.findOne({email:emailThisSession}).toIgnore; console.log(ignoreList) 请注意,控制台记录url变量的确会打印我要附加到数组的值! 我尝试了在Schema构建器和文档创建中可以想到的任何格式组合,但是找不到合适的方法来完成它! 任何帮助将不胜感激!

更新,使用诺言也不起作用

undefined

在按以下方式调整架构时:

User.findOne({email:emailThisSession}).then((currentUser)=>{ //adding .exec() after findOne({query}) does not help as in User.findOne({email:emailThisSession}).exec().then(...)
            console.log(currentUser.toIgnore,url) //output is empty array and proper value for url variable,empty array meaning []
            currentUser.toIgnore.push(url)
        });

解决方

我只需要将更新命令更改为

const userSchema = new Schema({
    email: String,toIgnore: []
})

感谢@yaya!

解决方法

无法在带有猫鼬的文档中添加数组元素

  1. 将架构定义为:
const UserSchema = new mongoose.Schema({
  ...
  toIgnore: [{toIgnoreURL: String}]
})
  1. 然后您可以创建一个像这样的对象:
new User({
  ...,toIgnore: [] // <-- optional,you can remove it
})
  1. 要检查值:
User.findOne({...}).then(user => {
  console.log(user.toIgnore)
});
  1. 您的更新声明应为:
User.update(
  {email: emailThisSession},{$push: {toIgnore: {toIgnoreURL: url}}}
).then(user => {
  console.log(user)
})

因此,在您的情况下,这是未定义的:

User.findOne({email:emailThisSession}).toIgnore

由于findOne是异步的。要获得结果,您可以将其传递给回调函数,也可以使用promise(User.findOne({...}).then(user => console.log(user.toIgnore))

更新:

在按以下方式调整架构时:new Schema({...,toIgnore: []})

这是您的更新问题。您应该将其更改回:toIgnore: [{toIgnoreURL: String}]