Node.js 无法检查mongoose中的嵌套模型中是否存在该值

Node.js 无法检查mongoose中的嵌套模型中是否存在该值,node.js,express,mongoose,Node.js,Express,Mongoose,我正在创建投票应用程序。我的模式定义如下 var mongoose = require('mongoose'); mongoose.Promise = global.Promise; mongoose.connect('mongodb://localhost:27017/pollApp'); var userSchema = new mongoose.Schema({ username: { type: String, required: true}, phonenumber:

我正在创建投票应用程序。我的模式定义如下

var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/pollApp');

var userSchema = new mongoose.Schema({
    username: { type: String, required: true},
    phonenumber: { type: String, required: true, unique: true}
});

var option = new mongoose.Schema({
    title: {type: String, required: true},
    votes: { type: Number, default: 0 },
    voterList: {type: []}
});

var poll = new mongoose.Schema({
    question: { type: String, required: true, unique: true},
    options: { type: [option], required: true},
    showVoters: {type: Boolean, default: false}
});

mongoose.user = mongoose.model('User', userSchema);
mongoose.poll = mongoose.model('Poll', poll);
module.exports = mongoose;

voterList将包含所有投票者的姓名。
在添加投票之前,我想检查用户是否已经对投票进行了投票(需要检查每个voterList数组中是否存在用户)。
如何完成此操作?

如果希望voterList数组中的值唯一,可以使用$addToSet在voterList中推送用户

但是如果你想做一些验证。最好执行get查询,检查用户是否已存在于数组中

如果是,抛出一条消息,说明用户已投票,否则将用户添加到voterlist

要检查voterList数组中是否已经存在用户,实际上非常简单

您可以使用如下所示的查找查询:

find({voterList:'585ce839c84f5d3d1ef15d56'})


即使voterList是一个数组,mongo也会查看提供的值是否存在于数组中。

如果希望voterList数组中的值唯一,可以使用$addToSet在voterList中推送用户

但是如果你想做一些验证。最好执行get查询,检查用户是否已存在于数组中

如果是,抛出一条消息,说明用户已投票,否则将用户添加到voterlist

要检查voterList数组中是否已经存在用户,实际上非常简单

您可以使用如下所示的查找查询:

find({voterList:'585ce839c84f5d3d1ef15d56'})


即使voterList是一个数组,mongo也会查看提供的值是否存在于数组中。

我想这可能是您想要的:我想这可能是您想要的:@sudheer让我知道这是否是您正在寻找的for@sudheer让我知道这是否是你想要的